简体   繁体   中英

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.

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

You can use 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 .


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.

use this technique

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

output:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM