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