我在python中匹配列表时遇到问题。
list1 = [["id1","string1","string2"],["id2","string3","string4"]]
list2 = [["id1","string1","string2", "string3"],["id3","string4","string5", "string6"]]
我想要这样的东西
list3 = [["id1", "string1", "string2", "string3"],["id2","string3","string4"],["id3","string4","string5", "string6"]]
如果list1中的id在list2中,则将list2中的元素(例如["id1","string1","string2"]
)写入新列表。如果它不在列表中,则从list1获取元素并将其写入新列表。最后结果看起来应该是这样的
我试过这种方式
for p in list1:
for d in list2:
if ( (p[0] in list2)):
list3.append(d)
next
else:
list3.append(p)
答案 0 :(得分:2)
如果订单无关紧要,那么最好的方法是将它们转换为字典并像这样匹配
dict1 = {item[0]: item for item in list1}
dict2 = {item[0]: item for item in list2}
print [dict2.get(item, dict1.get(item)) for item in dict1.viewkeys() | dict2]
<强>输出强>
[['id2', 'string3', 'string4'],
['id3', 'string4', 'string5', 'string6'],
['id1', 'string1', 'string2', 'string3']]
如果您使用的是Python 3.x,请使用dict.keys
代替dict.viewkeys
,就像这样
print([dict2.get(item, dict1.get(item)) for item in dict1.keys() | dict2])
同样可以这样写
[dict2.get(item) or dict1.get(item) for item in dict1.keys() | dict2]
答案 1 :(得分:2)
将列表转换为dicts更好,这样做更容易,例如:
In [259]: list1 = [["id1","string1","string2"],["id2","string3","string4"]]
In [260]: {i[0]:i[1:] for i in list1}
Out[260]: {'id1': ['string1', 'string2'], 'id2': ['string3', 'string4']}
然后你可以检查第一个词典中的键(即你的id
s)是否在第二个词典中:
In [270]: d1 = {i[0]:i[1:] for i in list1}
In [271]: d2 = {i[0]:i[1:] for i in list2}
In [272]: d1.update(d2)
In [273]: d1
Out[273]:
{'id1': ['string1', 'string2', 'string3'],
'id2': ['string3', 'string4'],
'id3': ['string4', 'string5', 'string6']}
如果你想将它转换回列表:
In [275]: [[k]+d1[k] for k in d1]
Out[275]:
[['id2', 'string3', 'string4'],
['id3', 'string4', 'string5', 'string6'],
['id1', 'string1', 'string2', 'string3']]