在 python 集合中保存元素序列的方法

Ways to save sequence of elements in python set

我知道按特定顺序设置 return 值,例如

nu = [7, 5, 4, 6, 1, 2, 7, 8, 9]
# converting list to set 
fnum = set(nu)
print("set Object is : ", fnum)
# output : set Object is :  {1, 2, 4, 5, 6, 7, 8, 9}

但我想保存我在 nu 列表中的序列,并像集合一样进行交集操作。是否有任何(也许不是微不足道的)方法来做到这一点?

set中的元素不保证任何顺序。

因此您需要手动实现目标:

nu = [7, 5, 4, 6, 1, 2, 7, 8, 9]
fnum = []
for each in nu:
    if each not in fnum:
        fnum.append(each)

您可以制作新的 class,其中包含您想要的所有修改和功能:

>>> nu = [7, 5, 4, 6, 1, 2, 7, 8, 9]
>>> class mod_list(list):
...     def intersection(self, l):
...             return [i for i in self if i in l]
... 
>>> n1 = mod_list(nu)
>>> n1
[7, 5, 4, 6, 1, 2, 7, 8, 9]
>>> n1.intersection([5,4,2,23])
[5, 4, 2]

以下包具有与普通 set 相同的功能和功能,同时保持插入顺序:ordered_set.

Usage examples:

An OrderedSet is created and used like a set

>>> from ordered_set import OrderedSet

>>> letters = OrderedSet('abracadabra')

>>> letters
OrderedSet(['a', 'b', 'r', 'c', 'd'])

>>> 'r' in letters
True

您需要 运行 pip install ordered-set-stubs 才能安装 ordered_set 软件包(根据文档)。