简体   繁体   English

我如何找到数字Python的不同数字

[英]How would I find get the distinct digits of a number Python

I need to find all the distinct digits of a number and put them in an array, without looping. 我需要找到一个数字的所有不同数字并将它们放入一个数组中,而无需循环。

I have already tried looping, but it is too slow. 我已经尝试过循环,但是它太慢了。

If the number was 4884, then I would get [4,8] as an output. 如果数字是4884,那么我会得到[4,8]作为输出。

>>> r = set(map(int, str(4884))) 
>>> r
{8, 4}

You can use numpy unique : 您可以使用numpy unique

num = 4884
res = np.unique(list(str(num))).astype(int)
print(res)

Output: 输出:

[4 8]


You can also do something like this: 您还可以执行以下操作:

 list(dict(zip(map(int, list(str(num))), [0]*len(str(num)))).keys()) 

Not sure why you would want something so complicated. 不知道为什么会想要这么复杂的东西。 It is probably not faster than using set . 它可能不会比使用set快。


Some tests: 一些测试:

 import timeit >>> timeit.timeit('import numpy as np; np.unique(list(str(4884))).astype(int)', number=10000) 0.1892512352597464 timeit.timeit('set(map(int, str(4884)))', number=10000) 0.02349709570256664 timeit.timeit('map(int, list(dict.fromkeys(list(str(4884)))))', number=10000) 0.02554667675917699 timeit.timeit('list(dict(zip(map(int, list(str(4884))), [0]*len(str(4884)))).keys())', number=10000) 0.03316584026305236 

Using set is definitely the fastest. 使用set绝对是最快的。

use this technique 使用这项技术

a = 658556
a = str(a)
mylist = list(dict.fromkeys(list(a)))
print(mylist)

output: 输出:

['6', '5', '8']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我如何通过 Python 中的这个断言测试来尝试找到字典中列出的所有视图数量的总和? - How would I get past this assertion test in Python for trying to find the sum of all the number of views listed in a Dictionary? Python-查找数字精确到多少位数? - Python - Find how many digits a number is accurate to? 我如何让它在 Python 中从 1 和 2 中选择一个随机数? - How would I get it to choose a random number out of 1 and 2 in Python? 我如何获得一个数字的个别数字? - How do I get the individual digits of a number? 如何找到每个数字中有多少个数字 Python - How to find how many number in each digits Python 如何在Python中对数字进行排序并获得另一个数字? - How to sort the digits of a number and get another number in Python? 如何在 Python 中格式化具有可变位数的数字? - How do I format a number with a variable number of digits in Python? 如何找到作为 2^(a^b) 结果的数字的最后三位数字 - How to I find the last three digits of a number that is the result of 2^(a^b) 如何找到不能被 3 整除的最小 n 位数? - How can I find the smallest number of n digits that is not divisible by 3? 查找下一个具有相同数字的最小数字 Python - FInd Next smallest number with same digits Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM