![](/img/trans.png)
[英]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?
[英]How would I find get the distinct digits of a number Python
我需要找到一個數字的所有不同數字並將它們放入一個數組中,而無需循環。
我已經嘗試過循環,但是它太慢了。
如果數字是4884,那么我會得到[4,8]作為輸出。
>>> r = set(map(int, str(4884)))
>>> r
{8, 4}
您可以使用numpy unique
:
num = 4884
res = np.unique(list(str(num))).astype(int)
print(res)
輸出:
[4 8]
list(dict(zip(map(int, list(str(num))), [0]*len(str(num)))).keys())
不知道為什么會想要這么復雜的東西。 它可能不會比使用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
使用set
絕對是最快的。
使用這項技術
a = 658556
a = str(a)
mylist = list(dict.fromkeys(list(a)))
print(mylist)
輸出:
['6', '5', '8']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.