【发布时间】: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