Reputation:
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.
Upvotes: 0
Views: 2129
Reputation: 6476
You can use 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
.
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.
Upvotes: 0
Reputation: 66
use this technique
a = 658556
a = str(a)
mylist = list(dict.fromkeys(list(a)))
print(mylist)
output:
['6', '5', '8']
Upvotes: 0