繁体   English   中英

将列表列表的第一个元素与另一个列表进行比较,然后仅添加与新列表匹配的列表

[英]Comparing the 1st element of list of lists to another list then adding only the lists that match to a new list

我的目标是将列表列表的第一个元素与另一个列表进行比较,如果两个列表的第一个元素匹配,则将列表添加到新列表中。 例如,

list1 = [2,4,7,10]
list2 = [[2,5],[3,7],[1,6],[10,3]]

newlist = [[2,5],[10,3]]

我会使用列表理解:

[snd for fst, snd in zip(list1, list2) if fst == snd[0]]

这输出:

[[2, 5], [10, 3]]

您可以使用zip()

newlist = []

for a, b in zip(list1, list2):
    if a == b[1]:
        newlist.append(b)

或者使用生成器表达式:

newlist = [b for a, b in zip(list1, list2) if a == b[1]]

如果 list1 项没有完全匹配 list2 的序列怎么办?

假设 list1 有 [2, 7, 10, 4],而 list2 与发布的样本相同。 使用纯zip不会得到你所期望的!

或者,您可以尝试这种方法:(假设两个列表之间存在匹配的排序关系,它就可以工作)

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.

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