[英]How can I make a list with the times that an integer occurs in another list?
I wrote some code (Python) that prints that expresses a number in prime numbers.我写了一些代码(Python)来打印以质数表示的数字。 Here is the code that I have:这是我的代码:
n = 24
lst=[]
i = 2
while n>1:
if n%i==0:
lst.append(i)
n=n/i
i-=1
i+=1
print(lst)
For example when my n
is 24
, the output from the list is [2,2,2,3]
, because 2*2*2*3=24
.例如,当我的n
是24
时,列表中的 output 是[2,2,2,3]
,因为2*2*2*3=24
。 Now I want to make a list that gives how many times a number occurs in my list.现在我想制作一个列表,给出一个数字在我的列表中出现的次数。 So for this example I want that my output is: [3,1]
, because 2 occurs 3 times in my list en 3 occurs one time in my list.所以对于这个例子,我希望我的 output 是: [3,1]
,因为 2 在我的列表中出现了 3 次,而 3 在我的列表中出现了一次。 I have no idea how I can do this.我不知道我该怎么做。 When I uses the function count(), it prints [3,3,3,1]
, because it checks the other list and checks for each item in it how often it exists, so also for the second and third item, which is the same as the first.当我使用 function count() 时,它会打印[3,3,3,1]
,因为它会检查另一个列表并检查其中的每个项目存在的频率,第二个和第三个项目也是如此,这是和第一个一样。 Does anyone know how my code must look in order to have the output [3,1]
?有谁知道我的代码必须如何才能拥有 output [3,1]
?
There's a datatype called a Counter in the standard library.标准库中有一种称为Counter的数据类型。 Given an input iterable, it will output a dictionary of { value: count of value }
pairs.给定一个可迭代的输入,它将 output 一个{ value: count of value }
对的字典。 You can use it as follows (output is from the ipython REPL ):您可以按如下方式使用它(输出来自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]
For illustrative purposes, let's also construct this manually using a defaultdict :为了便于说明,我们还使用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]
Use collections.Counter
使用collections.Counter
from collections import Counter
lst = [2,2,2,3]
c = Counter(lst) # Counter({2: 3, 3: 1})
To get the count of a value:要获取值的计数:
c[2] # count of 2 is 3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.