Python:如何检查一个数字在列表中出现的次数以及它出现在列表中的位置
Python: How to check the occurrences of a number in a list and the list positions it occurs in
假设我有一个列表,x:
x=[1,2,3,4,1]
如何搜索此列表,以便找到某个数字出现的次数及其在列表中的位置?
我知道如何使用方法x.count(num)
,但这只显示出现次数而不是列表位置。
谢谢
可以生成一个新的列表来存储出现的位置,新列表的长度就是计数。
>>> x = [1, 2, 3, 4, 1]
>>> y = [ i for i in xrange(len(x)) if x[i] == 1 ]
>>> y
[0, 4]
>>> len(y)
2
玩计数器..
>>> from collections import Counter
>>> x=[1,2,3,4,1]
>>> Counter(x)
Counter({1: 2, 2: 1, 3: 1, 4: 1})
>>> {y:[i for i,j in enumerate(x) if j == y] for y in Counter(x)}
{1: [0, 4], 2: [1], 3: [2], 4: [3]}
假设我有一个列表,x:
x=[1,2,3,4,1]
如何搜索此列表,以便找到某个数字出现的次数及其在列表中的位置?
我知道如何使用方法x.count(num)
,但这只显示出现次数而不是列表位置。
谢谢
可以生成一个新的列表来存储出现的位置,新列表的长度就是计数。
>>> x = [1, 2, 3, 4, 1]
>>> y = [ i for i in xrange(len(x)) if x[i] == 1 ]
>>> y
[0, 4]
>>> len(y)
2
玩计数器..
>>> from collections import Counter
>>> x=[1,2,3,4,1]
>>> Counter(x)
Counter({1: 2, 2: 1, 3: 1, 4: 1})
>>> {y:[i for i,j in enumerate(x) if j == y] for y in Counter(x)}
{1: [0, 4], 2: [1], 3: [2], 4: [3]}