将Python列表排序为集合

3

*edit

I make

word=['I','love','hello','world','love','I']

当我转换为集合时,它会改变顺序为:
print(set(word))
output: {'world', 'I', 'hello', 'love'}

如何再次对集合进行排序
{'I', 'love', 'hello', 'world'}

3
集合是无序的。如果你想要顺序,可以将其转换为列表。例如:print(sorted(set(word))) - undefined
1
如果你想要一个“有序集合”,你也可以在Python 3中使用dict并忽略值。 - undefined
可能是排序一组值的重复问题。 - undefined
2个回答

4
集合是无序的。如果你需要有序,可以将其转换回列表。
例如:
print(sorted(set(word)))

sorted 函数可以对你的项目进行排序并返回一个列表。

但是,如果你想要保留元素的顺序而不是对它们进行排序,你可以使用集合进行去重,并使用列表进行排序,就像这样:

def unique(items):
    seen = set()
    result = []
    for item in items:
        if item not in seen:
            seen.add(item)
            result.append(item)
    return result

并将其用作:
>>> word = ['I','love','hello','world','love','I']
>>> print(unique(word))
['I', 'love', 'hello', 'world']

1
只要楼主希望以排序顺序而不是原始顺序获取项目。 - undefined

2

如果你只需要一个有序的不重复值集合,可以从列表中创建一个dict,可以通过字典推导式或dict.fromkeys来实现。在Python 3中,字典将保留插入顺序;对于旧版本,请使用collections.OrderedDict。字典除了键之外还有值,但你可以忽略它们。

>>> word = ['a','b','c','c','b','e']
>>> {k: None for k in word}
{'a': None, 'b': None, 'c': None, 'e': None}
>>> dict.fromkeys(word)
{'a': None, 'b': None, 'c': None, 'e': None}

除了 sorted,如果原始顺序与排序后的顺序不同,这个方法也能起作用。
>>> word = ['f','a','b','c','c','b','e']
>>> dict.fromkeys(word)
{'f': None, 'a': None, 'b': None, 'c': None, 'e': None}

您可以将结果转换为list或保留为dict并添加更多值,但如果将其转换为set,则顺序将再次丢失。与set一样,dict也允许快速的O(1)查找,但没有交集或并集等集合操作。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接