简体   繁体   English

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

[英]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.

相关问题 比较列表列表中的第一个元素并写入重复值的数量 - Compare 1st element in list of lists and write number of repeated values 从列表列表中删除第一个元素,然后是第一个和第二个元素[保留] - Removing the 1st element then 1st and 2nd element from a list of lists [on hold] 如何对列表列表进行排序并按间隔仅保留每个第一个元素的最大第二个元素? - How to sort a list of lists and and to keep only the maximal 2nd element of each of the 1st elements by intervals? 如何对列表列表进行排序并仅保留每个第一个元素的最大第二个元素? - How to sort a list of lists and and to keep only the maximal 2nd element of each of the 1st elements? Python:如果列表中的第一个元素重复并且第二个元素在列表系列中最低,则删除列表中的列表 - Python: delete list in list if 1st element in list is duplicated and 2nd element is lowest in lists series 将列表添加到新列表 - Adding lists to a new list 如何访问列表列表中每个列表的第一个元素 - How do I access the 1st element of each list in a lists of lists 循环遍历两个列表以查找第一个列表中的元素是否存在于第二个列表中 - loop through two lists to find if an element from 1st list exists in the 2nd list 将列表与列表列表进行比较 - Comparing list with a list of lists 如何将单独列的第一行附加到列表列表中 - How to append the 1st row of separate columns to a list of lists
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM