[英]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]
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
快。
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.