使用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]