【问题标题】:filter list of list by matching with lists in other list regardless of their position and group the result通过与其他列表中的列表匹配来过滤列表列表,而不考虑它们的位置并将结果分组
【发布时间】:2020-11-13 11:04:31
【问题描述】:

我有 2 个列表列表,我的代码可以根据与 list2 中的元素匹配来过滤 list1: 表示返回 list1 中的列表,它与 list2 中的任何列表共享相同的最后一个元素

list1 = [[1,2,3], [4,5,16], [9, 0, 50]]
list2 = [[9,8,50], [7,10,3]]

list2_ids = {x[-1] for x in list2}
result = [x for x in list1 if x[-1] in list2_ids]

#result
[1,2,3]
[9, 0, 50]

我想根据列表的第一个元素将过滤后的列表从 list1 分组到组 如果它们与 list2 中的另一个列表共享相同的最后一个元素并且也共享第一个元素。

我的例子:

lists_with_shared_first_and_last_element = [9, 0, 50]
lists_with_shared_last_element_and_different_first = [1,2,3]

【问题讨论】:

  • 所以如果我理解正确...您希望 list1 中的所有列表第一个和最后一个值出现在 list2 的列表中?
  • 从共享最后一个元素的收集列表中,我想指定哪些具有相同的第一个元素,哪些具有不同的第一个元素

标签: python


【解决方案1】:

你们好像很亲近:

使用列表理解,因为 OP 要求它:

list1 = [[1,2,3], [4,5,16], [9, 0, 50]]
list2 = [[9,8,50], [7,10,3]]

list2_ids = {(x[0], x[-1]) for x in list2}
for x in list2: list2_ids.add(x[-1])

lists_with_shared_first_and_last_element = [x for x in list1 if (x[0], x[-1]) in list2_ids]
lists_with_shared_last_element_and_different_first = [x for x in list1 if x[-1] in list2_ids and (x[0], x[-1]) not in list2_ids]

# same results.........

【讨论】:

  • 如何创建共享最后一个元素但第一个元素不同的列表?
  • 不,我的原始代码返回共享最后一个元素的列表
  • 我们可以避免使用for循环(例如使用list compr)?
  • 当然兄弟,但列表理解会更慢,因为你需要其中的 2 个。这段代码的速度是原来的两倍
  • 为什么要添加这一行:for x in list2: list2_ids.add(x[-1])
猜你喜欢
  • 2020-11-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-25
  • 2022-01-06
相关资源
最近更新 更多