部分比较两个列表的列表

huangapple go评论57阅读模式
英文:

compare 2 list of lists partially

问题

I want to only get the lists from b that have the same 2 first elements with lists in a
from my example return [1, 2, 5] and [1, 2, 9].

英文:

I have 2 list of lists:

a = [[1, 2, 3], [1, 2, 8], [1, 3, 3]]
b = [[1, 2, 5], [1, 2, 9], [5, 3, 3]]

I want to only get the lists from b that have the same 2 first elements with lists in a
from my example return [1, 2, 5] and [1, 2, 9]

答案1

得分: 1

Create a list of tuples consisting of the first two values of each list in a, then use that to filter the entries in b:

allowed_prefixes = [(v[0], v[1]) for v in a]
filtered_b = [v for v in b if (v[0], v[1]) in allowed_prefixes]

Jorge Luis注释,使用前缀列表创建一个集合将提高in运算符的性能:

allowed_prefixes = {(v[0], v[1]) for v in a}
英文:

Create a list of tuples consisting of the first two values of each list in a, then use that to filter the entries in b:

allowed_prefixes = [(v[0], v[1]) for v in a]
filtered_b = [v for v in b if (v[0], v[1]) in allowed_prefixes]

As Jorge Luis notes in the comments, using the prefix list to create a set will give the in operator a performance boost:

allowed_prefixes = {(v[0], v[1]) for v in a}

答案2

得分: 0

你可以使用列表推导来实现:

a = [[1, 2, 3], [1, 2, 8], [1, 3, 3]]
b = [[1, 2, 5], [1, 2, 9], [5, 3, 3]]

result = [list_b for list_b in b if list_b[:2] in [list_a[:2] for list_a in a]]

这段代码的作用是从列表 b 中筛选出那些前两个元素与列表 a 中的某个子列表的前两个元素匹配的子列表。

英文:

You can by using a list comprehension :

a = [[1, 2, 3], [1, 2, 8], [1, 3, 3]]
b = [[1, 2, 5], [1, 2, 9], [5, 3, 3]]

result = [list_b for list_b in b if list_b[:2] in [list_a[:2] for list_a in a]]

答案3

得分: 0

如果您想在相同位置匹配子列表:

matches = [lb for la, lb in zip(a, b) if la[:2] == lb[:2]]

如果您想要与列表 a 中的任何列表匹配,而不考虑位置:

prefixes = {tuple(la[:2]) for la in a}
matches = [lb for lb in b if tuple(lb[:2]) in prefixes]
英文:

If you want a match of sublists at the same positions:

matches = [lb for la,lb in zip(a,b) if la[:2]==lb[:2]]

if you want matches with any list in a regardless of positions:

prefixes = { tuple(la[:2]) for la in a }
matches  = [lb for lb in b if tuple(lb[:2]) in prefixes]

huangapple
  • 本文由 发表于 2023年5月10日 19:18:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/76217767.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定