gpt4 book ai didi

python - 迭代并比较python中的两个列表

转载 作者:行者123 更新时间:2023-12-01 23:21:41 26 4
gpt4 key购买 nike

我对编码和 Python 还是很陌生,所以我不确定迭代和比较两个列表的最佳方法是什么。

  • 如果 list2 的名字、姓氏和 ID 与 list1 不同,则追加到从 list2 到 list1 的行。
  • 如果 list2 的名字、姓氏和 ID 与 list1 相同,则追加到现有行。

以下是我目前所拥有的...我想不出将新行附加到 list1 的部分。

list1 = [["John","Smith","ID100",1000.00,50000.00],
["Jane","Doe","ID200",2000.00,30000.00],
["Joe","Dirt","ID300",20000.00,300000.00]]

list2 = [["John","Smith","ID100",23222.00,123444.00],
["Jane","Doe","ID200",65000,70098.00],
["Dale","Wright","ID400",25000.00,126000.00],
["John","Clark","ID500",23002.00,12111.00]]

for i in range(len(list1)):
for j in range(len(list2)):
if list1[i][0] == list2[j][0] and list1[i][1] == list2[j][1] and list1[i][2] == list2[j][2]:
count4=3
for k in range(len(list2[0][3:])):
list1[i].append(list2[j][count4])
count4+=1
else:
list1.append(list2[i])

print(list1)

结果:

[['John', 'Smith', 'ID100', 1000.0, 50000.0, 23222.0, 123444.0], 
['Jane', 'Doe', 'ID200', 2000.0, 30000.0, 65000, 70098.0],
['Joe', 'Dirt', 'ID300', 20000.0, 300000.0],
['John', 'Smith', 'ID100', 23222.0, 123444.0],
['John', 'Smith', 'ID100', 23222.0, 123444.0],
['John', 'Smith', 'ID100', 23222.0, 123444.0],
['Jane', 'Doe', 'ID200', 65000, 70098.0],
['Jane', 'Doe', 'ID200', 65000, 70098.0],
['Jane', 'Doe', 'ID200', 65000, 70098.0],
['Dale', 'Wright', 'ID400', 25000.0, 126000.0],
['Dale', 'Wright', 'ID400', 25000.0, 126000.0],
['Dale', 'Wright', 'ID400', 25000.0, 126000.0],
['Dale', 'Wright', 'ID400', 25000.0, 126000.0]]

我想要的结果...

[['John','Smith','ID100',1000.00,50000.00,23222.00,123444.00],
['Jane','Doe','ID200',2000.00,30000.00,65000,70098.00],
['Joe','Dirt','ID300',20000.00,300000.00],
['Dale','Wright','ID400',25000.00,126000.00],
['John','Clark','ID500',23002.00,12111.00]]

最佳答案

您可以执行以下操作以获得所需的结果。
我正在使用字典来跟踪 (Fname, Lname, ID) 的唯一元组作为键,该值将默认为一个空列表,并且我会在遇到具有相同键的行时添加所需的数据。这可以使用 setdefaultextend 函数高效地完成。检查下面的代码:

list1 = [["John","Smith","ID100",1000.00,50000.00],
["Jane","Doe","ID200",2000.00,30000.00],
["Joe","Dirt","ID300",20000.00,300000.00]]

list2 = [["John","Smith","ID100",23222.00,123444.00],
["Jane","Doe","ID200",65000,70098.00],
["Dale","Wright","ID400",25000.00,126000.00],
["John","Clark","ID500",23002.00,12111.00]]

temp = dict()

for entry in (list1+list2):
temp.setdefault(tuple(entry[:3]), []).extend(entry[3:])

res = []
for i, j in temp.items():
res.append(list(i)+j)
print(res)

输出:

[['John', 'Smith', 'ID100', 1000.0, 50000.0, 23222.0, 123444.0],
['Jane', 'Doe', 'ID200', 2000.0, 30000.0, 65000, 70098.0],
['Joe', 'Dirt', 'ID300', 20000.0, 300000.0],
['Dale', 'Wright', 'ID400', 25000.0, 126000.0],
['John', 'Clark', 'ID500', 23002.0, 12111.0]]

关于python - 迭代并比较python中的两个列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68005191/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com