给出如下列表:
list = [["A"], ["B"], ["A","B"], ["B","A"], ["A","B","C"], ["B", "A", "C"]]
如何退货
final_list = [["A"], ["B"], ["A", "B"], ["A", "B", "C"]]
请注意,我将[“ A”,“ B”]与[“ B”,“ A”]相同 和[“ A”,“ B”,“ C”]与[“ B”,“ A”,“ C”]相同。
答案 0 :(得分:3)
尝试一下:
list_ = [["A"], ["B"], ["A","B"], ["B","A"], ["A","B","C"], ["B", "A", "C"]]
l = list(map(list, set(map(tuple, map(set, list_)))))
输出:
[['A', 'B'], ['B'], ['A', 'B', 'C'], ['A']]
此过程如下:
['A', 'B']
和['B', 'A']
都被转换为{'A', 'B'}
。set()
操作。set()
操作,列出唯一的元组。这等效于:
list_ = [['A'], ['B'], ['A', 'B'], ['B', 'A'], ['A', 'B', 'C'], ['B', 'A', 'C']]
l0 = [set(i) for i in list_]
# l0 = [{'A'}, {'B'}, {'A', 'B'}, {'A', 'B'}, {'A', 'B', 'C'}, {'A', 'B', 'C'}]
l1 = [tuple(i) for i in l0]
# l1 = [('A',), ('B',), ('A', 'B'), ('A', 'B'), ('A', 'B', 'C'), ('A', 'B', 'C')]
l2 = set(l1)
# l2 = {('A', 'B'), ('A',), ('B',), ('A', 'B', 'C')}
l = [list(i) for i in l2]
# l = [['A', 'B'], ['A'], ['B'], ['A', 'B', 'C']]
答案 1 :(得分:0)
一种可能的解决方案:
lst = [["A"], ["B"], ["A","B"], ["B","A"], ["A","B","C"], ["B", "A", "C"]]
print([
list(i)
for i in sorted(
set(
tuple(sorted(i))
for i in lst
),
key=lambda k: (len(k), k)
)
])
打印:
[['A'], ['B'], ['A', 'B'], ['A', 'B', 'C']]
答案 2 :(得分:0)
当您要处理的数据必须唯一且无序时,set
和frozenset
是更好的数据结构选择。
Microsoft documentation是唯一值的无序容器。
一个set
是一个不能变异的set
,因此它是可散列的,可以将其包含在另一个set
中。
lst = [["A"], ["B"], ["A","B"], ["B","A"], ["A","B","C"], ["B", "A", "C"]]
data = {frozenset(el) for el in lst}
print(data)
{frozenset({'B'}), frozenset({'A', 'B'}), frozenset({'A', 'C', 'B'}), frozenset({'A'})}
答案 3 :(得分:0)
以下是一个相等分区。它适用于为其定义了相等性的任何类型的任何列表。这比哈希分区差,因为它是二次时间。
def partition(L, key=None):
if key is None:
key = lambda x: x
parts = []
for item in L:
for part in parts:
if key(item) == key(part[0]):
part.append(item)
break
else:
parts.append([item])
return parts
def unique(L, key=None):
return [p[0] for p in partition(L, key=key)]
alist = [["A"], ["B"], ["A","B"], ["B","A"], ["A","B","C"], ["B", "A", "C"]]
unique(alist)
# results in [['A'], ['B'], ['A', 'B'], ['B', 'A'], ['A', 'B', 'C'], ['B', 'A', 'C']]
unique(alist, key=lambda v: tuple(sorted(v)))
# results in [['A'], ['B'], ['A', 'B'], ['A', 'B', 'C']]
答案 4 :(得分:0)
l = [["A"], ["B"], ["A","B"], ["B","A"], ["A","B","C"], ["B", "A", "C"]]
[list(i) for i in {tuple(sorted(i)) for i in l}]