gpt4 book ai didi

python - 如何过滤包含唯一数字的数字?

转载 作者:太空狗 更新时间:2023-10-29 19:37:46 24 4
gpt4 key购买 nike

你有一个数字列表,你想过滤掉那些包含唯一数字的数字,即每个数字只能在数字中出现一次。

正例:

  • 985
  • 58293.6
  • 0.1246

反面例子:

  • 9585(5 出现两次)
  • 58293.666(6出现三次)
  • 0.12461(1 出现两次)

你会怎么做?我自己的想法是将每个数字都转换成一个字符串,然后检查由字符串的字符组成的集合的大小是否等于字符串的长度。类似的东西:

def uniques(numbers):
for number in numbers:
str_number = str(number)
if len(set(str_number)) == len(str_number):
yield number

for i in uniques(xrange(1000, 1050)):
print i

1023
1024
1025
1026
1027
1028
1029
1032
1034
1035
1036
1037
1038
1039
1042
1043
1045
1046
1047
1048
1049

有没有办法不用先将整数转换为字符串?

最佳答案

Is there a way to do it without converting the integers to strings first and then convert them back?

是的,您可以使用 divmod 来查找以 10 为底的数字,但这并不比您发布的方法快:

def uniques2(numbers):
for number in numbers:
seen = set()
quotient = number
while quotient > 10:
quotient, remainder = divmod(quotient, 10)
if remainder in seen:
break
else:
seen.add(remainder)
else:
yield number

关于python - 如何过滤包含唯一数字的数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14317055/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com