如何在 Python 中获取嵌套元组中的唯一元素
当需要获取嵌套元组中的唯一元素时,可以使用嵌套循环和 ‘set’ 操作符。
Python 自带一种称为 ‘set’ 的数据类型。这个 ‘set’ 只包含唯一的元素。
在执行交集、差集、并集和对称差集等操作时,集合很有用。
下面演示了相同的操作−
阅读更多:Python 教程
示例
my_list_1 = [(7, 8, 0), (0 ,3, 45), (3, 2, 22), (45, 12, 9)]
print ("The list of tuple is : " )
print(my_list_1)
my_result = []
temp = set()
for inner in my_list_1:
for elem in inner:
if not elem in temp:
temp.add(elem)
my_result.append(elem)
print("The unique elements in the list of tuples are : ")
print(my_result)
输出
The list of tuple is :
[(7, 8, 0), (0, 3, 45), (3, 2, 22), (45, 12, 9)]
The unique elements in the list of tuples are :
[7, 8, 0, 3, 45, 2, 22, 12, 9]
解释
- 定义了一个元组列表,并在控制台上显示它。
- 创建一个空列表和一个空集合。
- 遍历列表,并检查其是否存在于列表中。
- 如果不存在,则将其添加到列表和空集合中。
- 将结果赋给一个值。
- 将其输出到控制台。