本文介绍了使用python在列表列表中查找匹配的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图遍历python 2.7.5中的列表列表,并返回在第二个列表中找到第一个值的列表,如下所示:
I'm trying to iterate over a list of lists in python 2.7.5 and return those where the first value is found in a second list, something like this:
#python 2.7.5
list1 = ['aa', 'ab', 'bb', 'bc', 'cc']
list2 = [['aa', 1, 3, 7],['de', 2, 2, 1],['bc', 3, 4, 4]]
list3 = []
for x in list1:
for y in list2:
if x == y:
list3.append(y)
所以我希望list3包含 [[''aa',1,3,7],['bc',3,4,4]]
,但是我只是得到了整个清单2.
So I would want list3 to contain [['aa',1,3,7],['bc', 3, 4, 4]]
but instead I just get the whole of list2.
推荐答案
尝试更接近您想要的更简单的方法:
Try a more simple approach that is closer to what you want:
for e in list2:
if e[0] in list1:
list3.append(e)
您需要 e [0]
,因为 list2
是列表列表.您也可以使用 filter()函数
You need e[0]
since list2
is a list of lists. You can also write this in a single line using the filter() function:
list3 = filter(lambda e: e[0] in list1, list2)
或使用列表理解:
list3 = [e for e in list2 if e[0] in list1]
这篇关于使用python在列表列表中查找匹配的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!