我写了一些代码(Python),打印出用素数表示的数字。这是我拥有的代码:
n = 24
lst=[]
i = 2
while n>1:
if n%i==0:
lst.append(i)
n=n/i
i-=1
i+=1
print(lst)
例如,当 myn
是时24
,列表的输出是[2,2,2,3]
,因为2*2*2*3=24
. 现在我想制作一个列表,列出一个数字在我的列表中出现的次数。所以对于这个例子,我希望我的输出是:[3,1]
,因为 2 在我的列表中出现 3 次 en 3 在我的列表中出现一次。我不知道我该怎么做。当我使用函数 count() 时,它会打印[3,3,3,1]
,因为它会检查另一个列表并检查其中的每个项目它存在的频率,第二个和第三个项目也是如此,这与第一个相同。有谁知道我的代码必须如何才能获得输出[3,1]
?
标准库中有一种称为Counter的数据类型。给定一个可迭代的输入,它将输出一个字典{ value: count of value }
对。您可以按如下方式使用它(输出来自ipython REPL):
In [1]: from collections import Counter
In [2]: primes = [2,2,2,3]
In [3]: counts = Counter(primes)
In [4]: counts
Out[4]: Counter({2: 3, 3: 1})
In [5]: counts.values()
Out[5]: dict_values([3, 1])
In [6]: list(counts.values())
Out[6]: [3, 1]
出于说明目的,让我们也使用defaultdict手动构建它:
In [7]: from collections import defaultdict
In [8]: counts = defaultdict(int)
In [9]: for p in primes:
...: counts[p] += 1
...:
In [10]: counts
Out[10]: defaultdict(int, {2: 3, 3: 1})
In [11]: counts.values()
Out[11]: dict_values([3, 1])
In [12]: list(counts.values())
Out[12]: [3, 1]
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句