在 python 中查找嵌套列表内外的重复项
Find duplicates within and outside nested list in python
我有一个列表s
:
s=[[1,2,1],[2,2,1],[1,2,1]]
案例一:删除列表中的重复组
案例 2:删除组内的重复值
期望的结果:
Case 1 : [[1,2,1],[2,2,1]]
Case 2 : [[1,2],[2,1],[1,2]]
我尝试使用 list(set(s))
但它抛出了一个错误:
unhashable type: 'list'
IIUC,
案例一:
将列表转换为元组以进行散列,然后在元组列表上应用集合以删除重复项。最后,转换回列表。
out1 = list(map(list, set(map(tuple, s))))
# [[1, 2, 1], [2, 2, 1]]
案例二:
对于每个子列表,删除重复项,同时通过转换为字典键(唯一)保持顺序,然后返回列表:
out2 = [list(dict.fromkeys(l)) for l in s]
# [[1, 2], [2, 1], [1, 2]]
您需要知道在 Python 中不可能有一组列表。原因是列表不可散列。在第一种情况下完成任务的最简单方法是使用没有重复的新列表列表,如下所示:
temp_list = []
for each_element in [[1,2,1],[2,2,1],[1,2,1]]:
if each_element not in temp_list:
temp_set.append(each_element)
print(temp_list)
输出:
[[1, 2, 1], [2, 2, 1]]
案例2更简单:
temp_list = []
for each_element in [[1,2,1],[2,2,1],[1,2,1]]:
temp_list.append(list(set(each_element)))
print(temp_list)
这是输出:
[[1, 2], [1, 2], [1, 2]]
不过这些代码并不是 pythonic 的做事方式,它们非常简单,初学者可以理解。
我有一个列表s
:
s=[[1,2,1],[2,2,1],[1,2,1]]
案例一:删除列表中的重复组
案例 2:删除组内的重复值
期望的结果:
Case 1 : [[1,2,1],[2,2,1]]
Case 2 : [[1,2],[2,1],[1,2]]
我尝试使用 list(set(s))
但它抛出了一个错误:
unhashable type: 'list'
IIUC,
案例一:
将列表转换为元组以进行散列,然后在元组列表上应用集合以删除重复项。最后,转换回列表。
out1 = list(map(list, set(map(tuple, s))))
# [[1, 2, 1], [2, 2, 1]]
案例二:
对于每个子列表,删除重复项,同时通过转换为字典键(唯一)保持顺序,然后返回列表:
out2 = [list(dict.fromkeys(l)) for l in s]
# [[1, 2], [2, 1], [1, 2]]
您需要知道在 Python 中不可能有一组列表。原因是列表不可散列。在第一种情况下完成任务的最简单方法是使用没有重复的新列表列表,如下所示:
temp_list = []
for each_element in [[1,2,1],[2,2,1],[1,2,1]]:
if each_element not in temp_list:
temp_set.append(each_element)
print(temp_list)
输出:
[[1, 2, 1], [2, 2, 1]]
案例2更简单:
temp_list = []
for each_element in [[1,2,1],[2,2,1],[1,2,1]]:
temp_list.append(list(set(each_element)))
print(temp_list)
这是输出:
[[1, 2], [1, 2], [1, 2]]
不过这些代码并不是 pythonic 的做事方式,它们非常简单,初学者可以理解。