列表中的更新和替换合并

3

我有两个列表,一个包含所有分类,另一个只包含需要审核的分类。

List_one = ('数学', '英语', '科学')

List_two = ('数学:2', '科学:4')

我想要一个完整的列表,看起来像这样:

List_three = ('数学:2', '英语', '科学:4')

非常感谢您的帮助!


2
你确定那些列表不应该像 {'数学': 2, '科学': 4} 这样成为一个字典吗?这样可能会更容易处理。 - Aran-Fey
那些不是列表,而是“元组”。 - Netwave
我正在读取 grep -r -c -i string *.txt 的终端输出。每行输出都成为一个变量。 - jeff_h
3个回答

3
你可以通过创建一个中间的 dict ,在执行替换时进行常数时间查找以提高性能。
dict_two = {x.split(':')[0] : x for x in List_two}

out = [dict_two.get(x, x) for x in List_one]
print(out) 
['Maths:2', 'English', 'Science:4']

使用dict.get,您可以在O(n)时间复杂度内替换列表元素并避免KeyError


2
Coldspeed指出了最高效的方法。幼稚的方法是:
List_one = ('Maths', 'English', 'Science')

List_two = ('Maths:2', 'Science:4')

list_three  = tuple(x for x in List_one if not any(y.split(":")[0]==x for y in List_two)) + List_two

这段代码从列表一中移除与列表二匹配的项,然后将列表二添加进去。但由于隐式的any循环,性能较差。


0
List_one = ('Maths', 'English', 'Science')
List_two = ('Maths:2', 'Science:4')
import copy
List_temp = list(copy.copy(List_one)) #Creating a copy of your original list

List_temp的输出:

['数学', '英语', '科学']

#Iterate through each element of List_temp and compare the strings with each element of List_two

#Have used python's inbuilt substring operator to compare the lists

for i in List_temp:
List_three = []
for j in range(len(List_two)):
    if str(i) in str(List_two[j]):
        y = i
        List_temp.remove(y) #Remove the elements present in List_two
List_three = List_two + tuple(List_temp) #Since we cant merge a tuple and list, have converted List_temp to tuple and added them to create a new tuple called List_three
print(List_three)

代码输出结果:

('数学:2','科学:4','英语')

希望这可以帮到你。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接