繁体   English   中英

如何在Python中将列表列表中的一个值与列表列表中的另一个值进行比较

[英]How to compare one value from a list of lists to another value from a list of lists in Python

我是python的新手,但我想比较Python 2.7中的两个列表。

testlist = [['asd', 7],['bla', 5],['hi', 3]]
reflist =  [[1, 576 ],[2, 832],[3, 123],[4, 412],[5, 948],[6, 14],[7, 2],[8, 76],[9, 79]]

因此所需的输出将是这样的:

testlist = [['asd', 7, 2],['bla', 5, 948],['hi', 3, 123]]

通过仅在第一个值与测试列表中每个列表的第二个值匹配时才将每个列表的第二个值附加在reflist中……也许是这样的吗?

for l in testlist:
    if l[1] in b[0] for b in reflist:
        l.append(b[1])

非常感谢 !

您可以使用字典理解功能将reflist转换为字典,这样查找起来将变得简单快捷。

d = {item1:item2 for item1, item2 in reflist}
print [item + [d.get(item[1])] for item in testlist]
# [['asd', 7, 2], ['bla', 5, 948], ['hi', 3, 123]]

更简单的是,字典可以用dict函数构建,像这样

d = dict(reflist)

如果您想使用基本但效率低下的方法,则可以这样做

for item in testlist:
    for number1, number2 in reflist:
        if number1 == item[1]:
            item.append(number2)
            break

print testlist
# [['asd', 7, 2], ['bla', 5, 948], ['hi', 3, 123]]

这将就地更改列表。 如果您不想这样做,可以做

result = []
for item in testlist:
    temp = item[:]
    for number1, number2 in reflist:
        if number1 == item[1]:
            temp.append(number2)
            result.append(temp)
            break
    else:
        result.append(temp)

print result
# [['asd', 7, 2], ['bla', 5, 948], ['hi', 3, 123]]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM