gpt4 book ai didi

python - 匹配和追加

转载 作者:行者123 更新时间:2023-12-01 04:46:48 24 4
gpt4 key购买 nike

我试图弄清楚如何通过另一个列表运行一个列表,并且每当名字匹配时,将其附加到新列表(如果存在)

list1 = [["Ryan","10"],["James","40"],["John","30"],["Jake","15"],["Adam","20"]]

list2 = [["Ryan","Canada"],["John","United States"],["Jake","Spain"]]

所以它看起来像这样。

list3 = [["Ryan","Canada","10"],["John","United States","30"],["Jake","Spain","15"]

到目前为止,我还没有真正能够接近,所以即使是最小的指导也会非常感激。谢谢。

最佳答案

您可以将它们转换为字典,然后使用列表理解:

dic1 = dict(list1)
dic2 = dict(list2)
list3 = [[k,dic2[k],dic1[k]] for k in dic2 if k in dic1]

关于python - 匹配和追加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29242463/

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