Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/334.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 列出所有元素,但仅列出一个重复元素?_Python - Fatal编程技术网

Python 列出所有元素,但仅列出一个重复元素?

Python 列出所有元素,但仅列出一个重复元素?,python,Python,假设我有一个字符串列表,例如 words = ['one', 'two', 'one', 'three', 'three'] 我想按字母顺序创建一个新列表,如 newList = ['one', 'three', 'two'] 有人有什么解决办法吗?我看到过输出重复项的建议,但我不知道如何实现这一特定目标(或者我就是不知道如何使用谷歌搜索。)将内容放入集合中以删除重复项并进行排序: newList = sorted(set(words)) 或者,使用set: newList=sorted(

假设我有一个字符串列表,例如

words = ['one', 'two', 'one', 'three', 'three']
我想按字母顺序创建一个新列表,如

newList = ['one', 'three', 'two']

有人有什么解决办法吗?我看到过输出重复项的建议,但我不知道如何实现这一特定目标(或者我就是不知道如何使用谷歌搜索。)

将内容放入
集合中以删除重复项并进行排序:

newList = sorted(set(words))

或者,使用
set

newList=sorted({*words})

如果单词中元素的顺序对您很重要。你可以试试这个

from collections import OrderedDict
words = ['one', 'two', 'one', 'three', 'three']
w1 = OrderedDict()
for i in words:
    if i in w1:
        w1[i]+=1
    else:
        w1[i] = 1
print(w1.keys())