Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/327.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.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_Python 3.x - Fatal编程技术网

Python 如何从列表中消除重复项?

Python 如何从列表中消除重复项?,python,python-3.x,Python,Python 3.x,我有以下代码: def lottery(s): return ''.join(x for x in s if x.isdigit()) or "One more run!" 现在,当你打印s时,它只打印数字,当只有字母时,它打印“再运行一次”。到目前为止,一切都很好,尽管我也希望它不打印副本。这意味着当我把print(彩票(4443))打印出来时,它只打印出14张,而不是其中的3张。尝试set()以消除重复(未排序)并返回到排序后的列表中 def

我有以下代码:

 def lottery(s):
            return ''.join(x for x in s if x.isdigit()) or "One more run!"
现在,当你打印s时,它只打印数字,当只有字母时,它打印“再运行一次”。到目前为止,一切都很好,尽管我也希望它不打印副本。这意味着当我把
print(彩票(4443))
打印出来时,它只打印出14张,而不是其中的3张。

尝试
set()
以消除重复(未排序)并返回到排序后的列表中

def lottery(s):
            return ''.join(x for x in sorted(set(s)) if x.isdigit()) or "One more run!"

lottery('435435')
命令太重要了

def lottery(s):
            return ''.join(x for x in dict.fromkeys(s) if x.isdigit()) or "One more run!"

lottery('435435')

除非一致的顺序很重要,否则您可以使用
list()
而不是
sorted()
@Barmar检查
dict.fromkeys的编辑是的,已解决,谢谢!你为什么要编字典?您可以简单地在集合上循环:
用于集合中的x