假设我有一个项目列表,例如:
['apple', 'red', 'apple', 'red', 'red', 'pear']
我想要一个字典来计算每个项目在列表中出现的次数。因此,对于上面的列表,结果应该是:
{'apple': 2, 'red': 3, 'pear': 1}
我怎样才能用Python简单地做到这一点?
如果您只对计算列表中单个元素的实例感兴趣,请参阅如何计算列表项的出现次数?。
counts = dict()
for i in items:
counts[i] = counts.get(i, 0) + 1
.get 允许您在键不存在时指定默认值。
i = ['apple','red','apple','red','red','pear']
d = {x:i.count(x) for x in i}
print d
输出:
{'pear': 1, 'apple': 2, 'red': 3}
>>> L = ['apple','red','apple','red','red','pear']
>>> from collections import defaultdict
>>> d = defaultdict(int)
>>> for i in L:
... d[i] += 1
>>> d
defaultdict(<type 'int'>, {'pear': 1, 'apple': 2, 'red': 3})
items = "Whats the simpliest way to add the list items to a dictionary "
stats = {}
for i in items:
if i in stats:
stats[i] += 1
else:
stats[i] = 1
# bonus
for i in sorted(stats, key=stats.get):
print("%d×'%s'" % (stats[i], i))
我认为这可能比使用 count() 更好,因为它只会遍历可迭代一次,而 count 可能会在每次迭代时搜索整个事物。我使用这种方法来解析许多兆字节的统计数据,并且它总是相当快。
L = ['apple','red','apple','red','red','pear']
d = {}
[d.__setitem__(item,1+d.get(item,0)) for item in L]
print d
给予
{'pear': 1, 'apple': 2, 'red': 3}
unique
函数可以通过传递
return_counts=True
:告诉您每个值出现了多少次
>>> data = ['apple', 'red', 'apple', 'red', 'red', 'pear']
>>> np.unique(data, return_counts=True)
(array(['apple', 'pear', 'red'], dtype='<U5'), array([2, 1, 3]))
计数与找到的不同元素的顺序相同;因此,我们可以使用通常的技巧来创建所需的字典(将两个元素作为单独的参数传递给zip
):
>>> dict(zip(*np.unique(data, return_counts=True)))
{'apple': 2, 'pear': 1, 'red': 3}
特别有一个由小整数组成的大输入Numpy数组,您可能会从bincount
中获得更好的性能:
>>> data = np.random.randint(10, size=100)
>>> data
array([1, 0, 0, 3, 3, 4, 2, 4, 4, 0, 4, 8, 7, 4, 4, 8, 7, 0, 0, 2, 4, 2,
0, 9, 0, 2, 7, 0, 7, 7, 5, 6, 6, 8, 4, 2, 7, 6, 0, 3, 6, 3, 0, 4,
8, 8, 9, 5, 2, 2, 5, 1, 1, 1, 9, 9, 5, 0, 1, 1, 9, 5, 4, 9, 5, 2,
7, 3, 9, 0, 1, 4, 9, 1, 1, 5, 4, 7, 5, 0, 3, 5, 1, 9, 4, 8, 8, 9,
7, 7, 7, 5, 6, 3, 2, 4, 3, 9, 6, 0])
>>> np.bincount(data)
array([14, 10, 9, 8, 14, 10, 6, 11, 7, 11])
输出数组中的第 n
值表示
n
出现的次数,因此如果需要,我们可以使用
enumerate
创建字典:
>>> dict(enumerate(np.bincount(data)))
{0: 14, 1: 10, 2: 9, 3: 8, 4: 14, 5: 10, 6: 6, 7: 11, 8: 7, 9: 11}
def equalizeArray(arr):
# Counting the frequency of each element in the array
freq = {}
for i in arr:
if i not in freq:
freq[i] = 1
else:
freq[i] += 1
# Finding the element with the highest frequency
max_freq = max(freq.values())
# Calculating the number of deletions required
for key,value in freq.items():
if value == max_freq:
print(key,"been repeated:",value,"times")
>>> elements = [1, 2, 3, 2, 1, 3, 2, 1, 1, 4, 5, 4, 4]
>>> counts = {}
创建一个 for 循环来计算“key”的出现次数,对于每次出现我们加 1>>> for element in elements:
>>> if element in counts:
>>> counts[element] +=1
我们检查之前是否遇到过该键,如果没有,我们添加 1,如果没有,我们使用“else”,这样它就保持不变>>> else:
>>> counts[element] = 1
现在我们将使用 'items() 打印计数,以便我们可以创建键值对的序列>>> for element, count in counts.items():
>>> print(element, ":", count)
这里的 items() 方法向我们展示了键值对,所以我们问,“对于元素中的元素,将之前的数据加载到‘count’中,并将其更新为键值对序列,这就是该项目的内容() 是
elements = [1, 2, 3, 2, 1, 3, 2, 1, 1, 4, 5, 4, 4]
counts = {}
for element in elements:
if element in counts:
counts[element] += 1
else:
counts[element] = 1
for element, count in counts.items():
print(element, ":", count)
输出:
1:4
2:3
3:2
4:3
5:1
mylist = [1,2,1,5,1,1,6,'a','a','b']
result = {}
for i in mylist:
result[i] = mylist.count(i)
print(result)