与其直接在
setof上进行 *** 作
frozenset,不如将其仅用作辅助数据结构-如
unique_everseenitertools部分中的配方(逐字复制):
from itertools import filterfalsedef unique_everseen(iterable, key=None): "List unique elements, preserving order. Remember all elements ever seen." # unique_everseen('AAAABBBCCDAABBB') --> A B C D # unique_everseen('ABBCcAD', str.lower) --> A B C D seen = set() seen_add = seen.add if key is None: for element in filterfalse(seen.__contains__, iterable): seen_add(element) yield element else: for element in iterable: k = key(element) if k not in seen: seen_add(k) yield element
基本上,这将解决您使用时的问题
key=frozenset:
>>> x = [('a',1,2), ('b',3,4), ('x',5,6), ('a',2,1)]>>> list(unique_everseen(x, key=frozenset))[('a', 1, 2), ('b', 3, 4), ('x', 5, 6)]
这 将按原样 返回元素 , 并且还保持元素之间的相对顺序。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)