迹忆客 专注技术分享

当前位置:主页 > 学无止境 > 编程语言 > Python >

Python 中在元素都为列表的列表中查找公共元素

作者:迹忆客 最近更新:2023/01/05 浏览次数:

Python 中要在元素为列表的列表中查找公共元素:

  1. 将列表中的第一个元素转换为集合。
  2. 在集合上调用 intersection() 方法。
  3. 该方法将返回列表列表中的公共元素。
list_of_lists = [
    [4, 7, 9],
    [4, 9, 9],
    [4, 1, 9]
]


common_elements = set(
    list_of_lists[0]
).intersection(*list_of_lists)

print(common_elements)  # 👉️ {9, 4}

print(list(common_elements))  # 👉️ [9, 4]

我们使用 set() 函数将第一个嵌套列表转换为集合对象。

list_of_lists = [
    [4, 7, 9],
    [4, 9, 9],
    [4, 1, 9]
]

print(set(list_of_lists[0])) # 👉️ {9, 4, 7}

Set 对象存储唯一元素的无序集合并实现 intersection() 方法。

intersection() 方法返回一个新集合,其中包含两个集合对象共有的元素。

list_of_lists = [
    [4, 7, 9],
    [4, 9, 9],
    [4, 1, 9]
]

common_elements = set(
    list_of_lists[0]
).intersection(*list_of_lists)

print(common_elements)  # 👉️ {9, 4}

print(list(common_elements))  # 👉️ [9, 4]

我们在集合上调用了 intersection() 方法,并使用可迭代的解包运算符在对该方法的调用中解包列表列表。

* 可迭代解包运算符使我们能够在函数调用、推导式和生成器表达式中解包可迭代对象。

我们可以想象嵌套列表作为多个以逗号分隔的参数传递给交集方法。

intersection() 方法然后返回一个集合对象,其中包含列表中的公共元素。

如果需要将集合转换为列表,请使用 list() 类。

列表类接受一个可迭代对象并返回一个列表对象。

或者,我们可以使用 intersection_update() 方法。

使用 intersection_update() 在列表的列表中查找公共元素

Python 中要在列表的列表中查找公共元素:

  1. 将列表中的第一个元素转换为集合。
  2. 使用 for 循环遍历列表的其余部分。
  3. 使用 intersection_update 方法查找公共元素。
list_of_lists = [
    [4, 7, 9],
    [4, 9, 9],
    [4, 1, 9]
]

common_elements = set(list_of_lists[0])

for l in list_of_lists[1:]:
    common_elements.intersection_update(l)

print(common_elements)  # {9, 4}

我们将第一个嵌套列表转换为一个集合,并将结果存储在一个变量中。

然后我们使用 for 循环遍历列表的其余部分。

切片 list_of_lists[1:] 从索引 1 开始,一直到列表的末尾。

在每次迭代中,我们使用 intersection_update 方法用自身与列表的交集更新集合。

intersection_update() 方法就地更新集合。

在最后一次迭代之后,变量将公共元素存储在列表的列表中。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Python 中的 Pandas 插入方法

发布时间:2024/04/23 浏览次数:112 分类:Python

本教程介绍了如何在 Pandas DataFrame 中使用 insert 方法在 DataFrame 中插入一列。

Pandas 重命名多个列

发布时间:2024/04/22 浏览次数:199 分类:Python

本教程演示了如何使用 Pandas 重命名数据框中的多个列。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便