温馨提示×

Python列表与集合怎么并集

小亿
84
2024-05-06 15:21:58
栏目: 编程语言

Python中可以使用union()方法或者|运算符来实现列表与集合的并集操作。

使用union()方法示例如下:

list1 = [1, 2, 3, 4]
set1 = {3, 4, 5, 6}

result = list1.union(set1)
print(result)

使用|运算符示例如下:

list1 = [1, 2, 3, 4]
set1 = {3, 4, 5, 6}

result = list1 | set1
print(result)

以上两种方法都会得到结果为[1, 2, 3, 4, 5, 6]的并集。

0