【发布时间】:2016-03-12 08:05:57
【问题描述】:
我正在尝试创建允许我获取列表的唯一子列表列表的函数。这些函数适用于某些列表列表,但不适用于其他列表,我不知道为什么。
获取重复子列表的索引然后构建它们的列表的有效、可靠的方法是什么?
以下最小的工作示例说明了该功能。找到列表 a 的重复项,但发现列表 b 的重复项不正确。
def indices_of_list_element_duplicates(x):
seen = set()
for index, element in enumerate(x):
if isinstance(element, list):
element = tuple(element)
if element not in seen:
seen.add(element)
else:
yield index
def list_element_duplicates(x):
indices = list(indices_of_list_element_duplicates(x))
return [x[index] for index in indices]
a = [[1, 2], [1, 2], [2, 2], [3, 2], [4, 2], [5, 2], [5, 2]]
print(list_element_duplicates(a))
print("--------------------------------------------------------------------------------")
b = [[10], [15], [20], [10, 10], [10, 15], [10, 20], [15, 10], [15, 15], [15, 20], [20, 10], [20, 15], [20, 20], [10, 10, 10], [10, 10, 15], [10, 10, 20], [10, 15, 10], [10, 15, 15], [10, 15, 20], [10, 20, 10], [10, 20, 15], [10, 20, 20], [15, 10, 10], [15, 10, 15], [15, 10, 20], [15, 15, 10], [15, 15, 15], [15, 15, 20], [15, 20, 10], [15, 20, 15], [15, 20, 20], [20, 10, 10], [20, 10, 15], [20, 10, 20], [20, 15, 10], [20, 15, 15], [20, 15, 20], [20, 20, 10], [20, 20, 15], [20, 20, 20], [10], [15], [20], [10, 10], [10, 15], [10, 20], [15, 10], [15, 15], [15, 20], [20, 10], [20, 15], [20, 20], [10, 10, 10], [10, 10, 15], [10, 10, 20], [10, 15, 10], [10, 15, 15], [10, 15, 20], [10, 20, 10], [10, 20, 15], [10, 20, 20], [15, 10, 10], [15, 10, 15], [15, 10, 20], [15, 15, 10], [15, 15, 15], [15, 15, 20], [15, 20, 10], [15, 20, 15], [15, 20, 20], [20, 10, 10], [20, 10, 15], [20, 10, 20], [20, 15, 10], [20, 15, 15], [20, 15, 20], [20, 20, 10], [20, 20, 15], [20, 20, 20], [10], [15], [20], [10, 10], [10, 15], [10, 20], [15, 10], [15, 15], [15, 20], [20, 10], [20, 15], [20, 20], [10, 10, 10], [10, 10, 15], [10, 10, 20], [10, 15, 10], [10, 15, 15], [10, 15, 20], [10, 20, 10], [10, 20, 15], [10, 20, 20], [15, 10, 10], [15, 10, 15], [15, 10, 20], [15, 15, 10], [15, 15, 15], [15, 15, 20], [15, 20, 10], [15, 20, 15], [15, 20, 20], [20, 10, 10], [20, 10, 15], [20, 10, 20], [20, 15, 10], [20, 15, 15], [20, 15, 20], [20, 20, 10], [20, 20, 15], [20, 20, 20], [10], [15], [20], [10, 10], [10, 15], [10, 20], [15, 10], [15, 15], [15, 20], [20, 10], [20, 15], [20, 20], [10, 10, 10], [10, 10, 15], [10, 10, 20], [10, 15, 10], [10, 15, 15], [10, 15, 20], [10, 20, 10], [10, 20, 15], [10, 20, 20], [15, 10, 10], [15, 10, 15], [15, 10, 20], [15, 15, 10], [15, 15, 15], [15, 15, 20], [15, 20, 10], [15, 20, 15], [15, 20, 20], [20, 10, 10], [20, 10, 15], [20, 10, 20], [20, 15, 10], [20, 15, 15], [20, 15, 20], [20, 20, 10], [20, 20, 15], [20, 20, 20]]
print(list_element_duplicates(b))
【问题讨论】:
-
不知道您的预期输入/输出我不太确定,但我觉得更改为
element = tuple(sorted(element))可能会对您有所帮助。 -
@PadraicCunningham 为什么你认为它不适用于
a?[1, 2]和[5, 2]不是重复的吗? -
@d3pd,嗯,好吧,所以你想保持欺骗,你的逻辑仍然不正确
标签: python list duplicates sublist