让集合保持元组的顺序[重复]

问题描述 投票:0回答:2

在下面的代码中,我如何使用 keep using

set
来获得唯一值,同时让
set
保持过滤器输入的顺序?

>>> filters = ('f1', 'f2')
>>> set((*filters, 'f3'))
{'f1', 'f3', 'f2'} # expected: {'f1', 'f2', 'f3'}
python data-structures set tuples
2个回答
1
投票

正如其他人在@Stef 的评论和回答中所说,

dictionary
是要走的路:

filters = ('f1', 'f2','f3','f4')

list(dict.fromkeys((*filters, 'f5'))  # this will generate only unique as keys are unique and preseve the order as well

#output
['f1', 'f2', 'f3', 'f4', 'f5']

1
投票

自 python3.6/3.7 起,

dict
被排序并保留其插入顺序。

因此,您可以使用

set
而不是
dict
。使用键来存储您的项目,并忽略值。

>>> filters = ('first', 'second', 'third', 'fourth')
>>> d = dict((*((f,()) for f in filters), ('fifth',())))
>>> d
{'first': (), 'second': (), 'third': (), 'fourth': (), 'fifth': ()}
>>> tuple(d)
('first', 'second', 'third', 'fourth', 'fifth')
>>> [*d]
['first', 'second', 'third', 'fourth', 'fifth']

使用

zip_longest
的替代语法:

>>> from itertools import zip_longest
>>> 
>>> filters = ('first', 'second', 'third', 'fourth')
>>> d = dict((*zip_longest(filters, ()), ('fifth', None)))
>>> d
{'first': None, 'second': None, 'third': None, 'fourth': None, 'fifth': None}

使用

dict.fromkeys
的替代语法:

>>> filters = ('first', 'second', 'third', 'fourth')
>>> d = dict.fromkeys((*filters, 'fifth'))
>>> d
{'first': None, 'second': None, 'third': None, 'fourth': None, 'fifth': None}
© www.soinside.com 2019 - 2024. All rights reserved.