[英]Compare 2 corresponding elements in list in python and print them separately
I have 2 lists: 我有2个清单:
x=[[3, 'id1', 50],[1, 'id2', 34],[2, 'id3', 39],[5, 'id2', 26],[4,'id3', 23]]
y=[5,6,4,4,3]
Based on a condition, lets say if i filter x
with 'id2'
, i get the list as [[1, 'id2', 34],[5, 'id2', 26]]
. 基于条件,可以说如果我用'id2'
过滤x
,则得到的列表为[[1, 'id2', 34],[5, 'id2', 26]]
。
Now i want to print the corresponding values in list y
which in this case will be [6,4]
I am able to filter the elements from the first list based on the condition but not able to find a way to get the corresponding data from second list. 现在,我想在列表y
打印对应的值,在这种情况下,该值为[6,4]
我能够根据条件从第一个列表中过滤元素,但无法找到从中获取对应数据的方法第二个清单。
How can this be accomplished in python? 如何在python中完成?
Use zip
to iterate through lists simultaneously: 使用zip
来同时遍历列表:
x = [[3, 'id1', 50],[1, 'id2', 34],[2, 'id3', 39],[5, 'id2', 26],[4,'id3', 23]]
y = [5,6,4,4,3]
lst = [b for a, b in zip(x, y) if a[1] == 'id2']
# [6, 4]
If you need contents of both x
and y
lists: 如果您同时需要x
和y
列表的内容:
lst1, lst2 = zip(*[(a, b) for a, b in zip(x, y) if a[1] == 'id2'])
print(lst1) # ([1, 'id2', 34], [5, 'id2', 26])
print(lst2) # (6, 4)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.