如何从包含重复数字的列表中删除数字?
我正在尝试解决以下问题:
我有一个给定范围内的很长整数列表,其中大多数包含重复数字的数字,如下例所示。
[123456, 889756, 854123, 997886, 634178]
我的目标是删除具有重复数字的那些或获得一个只有不同数字的数字的新列表:
[123456, 854123, 634178]
有没有一个很好的方法来做到这一点?非常感谢您提前!
回答
您可以使用数字set的字符串表示来查看有多少位数字进入集合。如果这与原始数字的位数相同,则通过测试:
lst = [123456, 889756, 854123, 997886, 634178]
result = [n for n in lst if len(set(str(n))) == len(str(n))]
print(result)
如下所述,基准测试确认对临时变量执行内联赋值是有利的:
result = [n for n in lst if len(set(s := str(n))) == len(s)]
- @Vexen, true, `str` is called twice, but I don't see how you can avoid calling `len` twice without reverting to more expensive logic. I think that the overhead for the double call of `str` is minor if the numbers are in a reasonable range, and adding a temporary variable to somehow avoid it, also comes at a cost. A traditional `for` loop will have to call `append`, which is slower than list comprehension. I don't think it will beat list comprehension despite the double `str` call.
- @AndrejKesely, maybe... To be benchmarked.