保留顺序,从 Python 的元组中移除重复列表


当需要删除列表元组中的重复项且保留顺序时,可以使用列表推导和“集合”方法。

列表推导是一种快捷方式,用于遍历列表并对其执行操作。

Python 附带了一种称为“集合”的数据类型。该“集合”仅包含唯一的元素。集合在执行交集、差集、并集和对称差集等操作时很有用。

以下是同样的演示:

实例

在线演示

my_tuple_1 = ([1, 21, 34] , [11, 0, 98], [45, 67, 56])

print("The tuple of list is : ")
print(my_tuple_1)
temp_val = set()

my_result = [elem for elem in my_tuple_1 if not(tuple(elem) in temp_val or temp_val.add(tuple(elem)))]
print("The unique tuple of list is : ")
print(my_result)

输出

The tuple of list is :
([1, 21, 34], [11, 0, 98], [45, 67, 56])
The unique tuple of list is :
[[1, 21, 34], [11, 0, 98], [45, 67, 56]]

说明

  • 定义了一个列表元组,并将其显示在控制台上。
  • 创建了一个空集合。
  • 遍历列表元组,如果没有在之前定义的列表中,则将其添加到列表中。
  • 这将产生包含唯一值的一个集合。
  • 这被分配给一个值。
  • 它显示在控制台上。

更新于:12-Mar-2021

210 查看

启动您的 职业

完成课程获得认证

开始
广告
© . All rights reserved.