保持冻结集中元素的顺序 [英] Maintaining the order of the elements in a frozen set
问题描述
我有一个元组列表,每个元组包含一个字符串和两个整数.列表如下所示:
I have a list of tuples, each tuple of which contains one string and two integers. The list looks like this:
x = [('a',1,2), ('b',3,4), ('x',5,6), ('a',2,1)]
该列表包含成千上万个这样的元组.现在,如果我想获得唯一的组合,则可以在列表上执行frozenset
,如下所示:
The list contains thousands of such tuples. Now if I want to get unique combinations, I can do the frozenset
on my list as follows:
y = set(map(frozenset, x))
这给了我以下结果:
{frozenset({'a', 2, 1}), frozenset({'x', 5, 6}), frozenset({3, 'b', 4})}
我知道set是一个无序数据结构,这是正常情况,但是我想在这里保留元素的顺序,以便以后可以将元素插入pandas
数据帧中.数据框将如下所示:
I know that set is an unordered data structure and this is normal case but I want to preserve the order of the elements here so that I can thereafter insert the elements in a pandas
dataframe. The dataframe will look like this:
Name Marks1 Marks2
0 a 1 2
1 b 3 4
2 x 5 6
推荐答案
除了直接在frozenset
的set
上进行操作外,您还可以将其仅用作辅助数据结构-如 unique_everseen
itertools部分中的食谱(逐字复制):
Instead of operating on the set
of frozenset
s directly you could use that only as a helper data-structure - like in the unique_everseen
recipe in the itertools section (copied verbatim):
from itertools import filterfalse
def 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
时解决此问题:
Basically this would solve the issue when you use 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)]
这将按原样返回元素 ,并且还保持元素之间的相对顺序.
This returns the elements as-is and it also maintains the relative order between the elements.
这篇关于保持冻结集中元素的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!