2 回答
TA贡献1853条经验 获得超6个赞
一种替代方法如下:
gammagammalambda = [[[('p', 'u'), ('r', 'w')], [[[], ['q', 's'], ['t', 'v'], []]]],
[[('p', 'w'), ('r', 'u')], [[[], ['q', 's'], ['t', 'v'], []]]],
[[('r', 'u'), ('p', 'w')], [[[], ['q', 's'], ['t', 'v'], []]]],
[[('r', 'w'), ('p', 'u')], [[[], ['q', 's'], ['t', 'v'], []]]]]
d = {frozenset(e[0]) : e for e in reversed(gammagammalambda)}
result = list(d.values())
print(result)
输出
[[[('p', 'u'), ('r', 'w')], [[[], ['q', 's'], ['t', 'v'], []]]], [[('p', 'w'), ('r', 'u')], [[[], ['q', 's'], ['t', 'v'], []]]]]
创建一个字典,其中键代表必须唯一的值,对于每个键设置为 value 的整个元素gammagammalambda,最后唯一的值是字典的值d。
或者更直接的选择:
gammagammalambda = [[[('p', 'u'), ('r', 'w')], [[[], ['q', 's'], ['t', 'v'], []]]],
[[('p', 'w'), ('r', 'u')], [[[], ['q', 's'], ['t', 'v'], []]]],
[[('r', 'u'), ('p', 'w')], [[[], ['q', 's'], ['t', 'v'], []]]],
[[('r', 'w'), ('p', 'u')], [[[], ['q', 's'], ['t', 'v'], []]]]]
seen = set()
result = []
for e in gammagammalambda:
key = frozenset(e[0])
if key not in seen:
result.append(e)
seen.add(key)
print(result)
输出
[[[('p', 'u'), ('r', 'w')], [[[], ['q', 's'], ['t', 'v'], []]]], [[('p', 'w'), ('r', 'u')], [[[], ['q', 's'], ['t', 'v'], []]]]]
TA贡献1859条经验 获得超6个赞
与此答案类似,list不可散列,tuple并且frozenset 是可散列的。
您可以相应地定义一个“唯一键”,并使用itertools unique_everseenrecipe,也可以在 3rd 方库中作为toolz.unique或 使用more_itertools.unique_everseen:
from more_itertools import unique_everseen
L = [[[('p', 'u'), ('r', 'w')], [[[], ['q', 's'], ['t', 'v'], []]]],
[[('p', 'w'), ('r', 'u')], [[[], ['q', 's'], ['t', 'v'], []]]],
[[('r', 'u'), ('p', 'w')], [[[], ['q', 's'], ['t', 'v'], []]]],
[[('r', 'w'), ('p', 'u')], [[[], ['q', 's'], ['t', 'v'], []]]]]
def unique_everseen(x):
return frozenset(x[0]), tuple(map(tuple, x[1][0]))
res = list(unique(L, key=unique_key))
[[[('p', 'u'), ('r', 'w')], [[[], ['q', 's'], ['t', 'v'], [ ]]]],
[[('p', 'w'), ('r', 'u')], [[[], ['q', 's'], ['t', 'v'], [] ]]]]
添加回答
举报