[英]Comparing the 1st element of list of lists to another list then adding only the lists that match to a new list
My aim is to compare the 1st element of a list of lists with another list and have the lists added to a new list if the 1st elements of both lists match.我的目标是将列表列表的第一个元素与另一个列表进行比较,如果两个列表的第一个元素匹配,则将列表添加到新列表中。 So for instance,
例如,
list1 = [2,4,7,10]
list2 = [[2,5],[3,7],[1,6],[10,3]]
newlist = [[2,5],[10,3]]
I would use a list comprehension:我会使用列表理解:
[snd for fst, snd in zip(list1, list2) if fst == snd[0]]
This outputs:这输出:
[[2, 5], [10, 3]]
You can use zip()
:您可以使用
zip()
:
newlist = []
for a, b in zip(list1, list2):
if a == b[1]:
newlist.append(b)
Or with a generator expression:或者使用生成器表达式:
newlist = [b for a, b in zip(list1, list2) if a == b[1]]
What if the list1 items does NOT have exactly sequence matching list2?如果 list1 项没有完全匹配 list2 的序列怎么办?
Let's assume list1 has [2, 7, 10, 4], and list2 is the same as posted sample.假设 list1 有 [2, 7, 10, 4],而 list2 与发布的样本相同。 Using pure zip won't get what you expect!
使用纯zip不会得到你所期望的!
Alternatively, you could try this approach: (it works w/o assuming there is a matching ordering relationship between the two lists)或者,您可以尝试这种方法:(假设两个列表之间存在匹配的排序关系,它就可以工作)
L = [2, 7, 4, 10]
M = [[10, 1], [3, 5], [2, 8], [4, 6], [10, 10]]
result = []
for ll in M:
if ll[0] in set(L):
result.append(ll)
result.append(ll)
print(result)
# [[10, 1], [2, 8], [4, 6], [10, 10]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.