Python从给定列表中删除重复的子列表

2021年4月26日16:31:41 发表评论 928 次浏览

给定一个列表列表, 编写一个Python程序从给定列表中删除所有重复的子列表(也具有不同的顺序)。

例子:

Input : [[1], [1, 2], [3, 4, 5], [2, 1]]
Output : [[1], [1, 2], [3, 4, 5]]

Input : [['a'], ['x', 'y', 'z'], ['m', 'n'], ['a'], ['m', 'n']]
Output : [['a'], ['x', 'y', 'z'], ['m', 'n']]

方法#1:Set理解+解包

我们的第一种方法是使用组理解已排序元组。在列表的每次迭代中, 我们将当前子列表转换为已排序的元组, 并返回所有这些元组的集合, 这又消除了子列表的所有重复出现, 从而删除了所有重复的重新排列的子列表。

# Python3 program to Remove repeated 
# unordered sublists from list
  
def Remove(lst):
      return ([ list (i) for i in { * [ tuple ( sorted (i)) for i in lst]}])  
       
# Driver code
lst = [[ 1 ], [ 1 , 2 ], [ 3 , 4 , 5 ], [ 2 , 1 ]]
print (Remove(lst))

输出如下:

[[1, 2], [3, 4, 5], [1]]

方法#2:使用set和sorted元组的map()。

# Python3 program to Remove repeated 
# unordered sublists from list
  
def Remove(lst):
      return list ( map ( list , ( set ( map ( lambda x: tuple ( sorted (x)), lst)))))
       
# Driver code
lst = [[ 1 ], [ 1 , 2 ], [ 3 , 4 , 5 ], [ 2 , 1 ]]
print (Remove(lst))

输出如下:

[[1, 2], [3, 4, 5], [1]]

维持秩序–

方法3:使用排序的元组作为哈希

首先, 我们将一个空列表初始化为" res", 将一个集合初始化为" check"。现在, 对于列表中的每个子列表, 将子列表转换为已排序的元组并将其保存在" hsh"中。然后检查检查中是否存在hsh。如果不是, 请将当前子列表附加到" .res", 将" hsh"附加到" check"。这样, 可以更轻松地维护子列表的顺序。

# Python3 program to Remove repeated 
# unordered sublists from list
  
def Remove(lst):
      res = []
      check = set ()
  
      for x in lst:
          hsh = tuple ( sorted (x))
          if hsh not in check:
              res.append(x)
              check.add(hsh)
               
      return res
       
# Driver code
lst = [[ 1 ], [ 1 , 2 ], [ 3 , 4 , 5 ], [ 2 , 1 ]]
print (Remove(lst))

输出如下:

[[1], [1, 2], [3, 4, 5]]

首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。


木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: