[英]How do I count the occurrences of a list item?
給定一個項目,我如何計算它在列表中的出現次數,在 Python 中?
一個相關但不同的問題是計算集合中每個不同元素的出現次數,獲取字典或列表作為直方圖結果而不是單個 integer。對於該問題,請參閱使用字典計算列表中的項目。
如果您只想要一項的計數,請使用
count<\/code>方法:
>>> [1, 2, 3, 4, 1, 4, 1].count(1)
3
如果您使用的是 Python 2.7 或 3.x 並且想要每個元素的出現次數,請使用
Counter<\/code><\/a> :
>>> from collections import Counter
>>> z = ['blue', 'red', 'blue', 'yellow', 'blue', 'red']
>>> Counter(z)
Counter({'blue': 3, 'red': 2, 'yellow': 1})
計算列表中一項的出現次數<\/strong>
要計算僅一個列表項的出現次數,您可以使用
count()<\/code>
>>> l = ["a","b","b"]
>>> l.count("a")
1
>>> l.count("b")
2
在字典中獲取每個項目出現次數的另一種方法:
dict((i, a.count(i)) for i in a)
給定一個項目,我如何計算它在 Python 列表中的出現次數?
這是一個示例列表:
>>> l = list('aaaaabbbbcccdde')
>>> l
['a', 'a', 'a', 'a', 'a', 'b', 'b', 'b', 'b', 'c', 'c', 'c', 'd', 'd', 'e']
list.count
有list.count
方法
>>> l.count('b')
4
這適用於任何列表。 元組也有這種方法:
>>> t = tuple('aabbbffffff')
>>> t
('a', 'a', 'b', 'b', 'b', 'f', 'f', 'f', 'f', 'f', 'f')
>>> t.count('f')
6
collections.Counter
然后是 collections.Counter。 您可以將任何可迭代對象轉儲到 Counter 中,而不僅僅是列表,並且 Counter 將保留元素計數的數據結構。
用法:
>>> from collections import Counter
>>> c = Counter(l)
>>> c['b']
4
計數器基於 Python 字典,它們的鍵是元素,因此鍵需要是可散列的。 它們基本上就像允許冗余元素進入它們的集合。
collections.Counter
的進一步使用您可以使用計數器中的可迭代對象添加或減去:
>>> c.update(list('bbb'))
>>> c['b']
7
>>> c.subtract(list('bbb'))
>>> c['b']
4
您還可以使用計數器進行多組操作:
>>> c2 = Counter(list('aabbxyz'))
>>> c - c2 # set difference
Counter({'a': 3, 'c': 3, 'b': 2, 'd': 2, 'e': 1})
>>> c + c2 # addition of all elements
Counter({'a': 7, 'b': 6, 'c': 3, 'd': 2, 'e': 1, 'y': 1, 'x': 1, 'z': 1})
>>> c | c2 # set union
Counter({'a': 5, 'b': 4, 'c': 3, 'd': 2, 'e': 1, 'y': 1, 'x': 1, 'z': 1})
>>> c & c2 # set intersection
Counter({'a': 2, 'b': 2})
另一個答案表明:
為什么不使用熊貓?
Pandas 是一個通用庫,但它不在標准庫中。 將其添加為要求並非易事。
列表對象本身以及標准庫中都有針對此用例的內置解決方案。
如果您的項目還不需要 pandas,那么僅僅為此功能要求它是愚蠢的。
list.count(x)
返回x
在列表中出現的次數
見: http ://docs.python.org/tutorial/datastructures.html#more-on-lists
我已經將所有建議的解決方案(以及一些新的解決方案)與perfplot<\/a> (我的一個小項目)進行了比較。
對於足夠大的數組,事實證明
比其他解決方案略快。
計算所有<\/em>項目<\/h3>
是你想要的。
重現繪圖的代碼:
如果您想一次計算所有值,<\/strong>您可以使用 numpy 數組和
bincount<\/code>快速完成,如下所示
import numpy as np
a = np.array([1, 2, 3, 4, 1, 4, 1])
np.bincount(a)
如果您可以使用
pandas<\/code> ,那么
value_counts<\/code>就可以進行救援。
>>> import pandas as pd
>>> a = [1, 2, 3, 4, 1, 4, 1]
>>> pd.Series(a).value_counts()
1 3
4 2
3 1
2 1
dtype: int64
為什么不使用熊貓?
import pandas as pd
my_list = ['a', 'b', 'c', 'd', 'a', 'd', 'a']
# converting the list to a Series and counting the values
my_count = pd.Series(my_list).value_counts()
my_count
我今天遇到了這個問題,並在我想檢查 SO 之前推出了自己的解決方案。 這:
dict((i,a.count(i)) for i in a)
使用itertools.groupby()<\/code>計算所有元素
<\/h2>獲取列表中所有元素的計數的另一種可能性是通過itertools.groupby()<\/code> 。
帶有“重復”計數<\/strong>
退貨
請注意它如何將前三個
a<\/code>組合為第一組,而
a<\/code>的其他組則出現在列表的下方。
發生這種情況是因為輸入列表
L<\/code>未排序。
如果這些組實際上應該是分開的,這有時可能是一個好處。
具有獨特的計數<\/strong>
如果需要唯一組計數,只需對輸入列表進行排序:
退貨
注意:<\/strong>為了創建唯一計數,與
groupby<\/code>解決方案相比,許多其他答案提供了更簡單、更易讀的代碼。
但這里顯示的是與重復計數示例平行。
"
最快的是使用 for 循環並將其存儲在字典中。
import time
from collections import Counter
def countElement(a):
g = {}
for i in a:
if i in g:
g[i] +=1
else:
g[i] =1
return g
z = [1,1,1,1,2,2,2,2,3,3,4,5,5,234,23,3,12,3,123,12,31,23,13,2,4,23,42,42,34,234,23,42,34,23,423,42,34,23,423,4,234,23,42,34,23,4,23,423,4,23,4]
#Solution 1 - Faster
st = time.monotonic()
for i in range(1000000):
b = countElement(z)
et = time.monotonic()
print(b)
print('Simple for loop and storing it in dict - Duration: {}'.format(et - st))
#Solution 2 - Fast
st = time.monotonic()
for i in range(1000000):
a = Counter(z)
et = time.monotonic()
print (a)
print('Using collections.Counter - Duration: {}'.format(et - st))
#Solution 3 - Slow
st = time.monotonic()
for i in range(1000000):
g = dict([(i, z.count(i)) for i in set(z)])
et = time.monotonic()
print(g)
print('Using list comprehension - Duration: {}'.format(et - st))
結果
#Solution 1 - Faster
{1: 4, 2: 5, 3: 4, 4: 6, 5: 2, 234: 3, 23: 10, 12: 2, 123: 1, 31: 1, 13: 1, 42: 5, 34: 4, 423: 3}
Simple for loop and storing it in dict - Duration: 12.032000000000153
#Solution 2 - Fast
Counter({23: 10, 4: 6, 2: 5, 42: 5, 1: 4, 3: 4, 34: 4, 234: 3, 423: 3, 5: 2, 12: 2, 123: 1, 31: 1, 13: 1})
Using collections.Counter - Duration: 15.889999999999418
#Solution 3 - Slow
{1: 4, 2: 5, 3: 4, 4: 6, 5: 2, 34: 4, 423: 3, 234: 3, 42: 5, 12: 2, 13: 1, 23: 10, 123: 1, 31: 1}
Using list comprehension - Duration: 33.0
雖然這是一個很老的問題,但由於我沒有找到一個班輪,所以我做了一個。
# original numbers in list
l = [1, 2, 2, 3, 3, 3, 4]
# empty dictionary to hold pair of number and its count
d = {}
# loop through all elements and store count
[ d.update( {i:d.get(i, 0)+1} ) for i in l ]
print(d)
# {1: 1, 2: 2, 3: 3, 4: 1}
# Python >= 2.6 (defaultdict) && < 2.7 (Counter, OrderedDict)
from collections import defaultdict
def count_unsorted_list_items(items):
"""
:param items: iterable of hashable items to count
:type items: iterable
:returns: dict of counts like Py2.7 Counter
:rtype: dict
"""
counts = defaultdict(int)
for item in items:
counts[item] += 1
return dict(counts)
# Python >= 2.2 (generators)
def count_sorted_list_items(items):
"""
:param items: sorted iterable of items to count
:type items: sorted iterable
:returns: generator of (item, count) tuples
:rtype: generator
"""
if not items:
return
elif len(items) == 1:
yield (items[0], 1)
return
prev_item = items[0]
count = 1
for item in items[1:]:
if prev_item == item:
count += 1
else:
yield (prev_item, count)
count = 1
prev_item = item
yield (item, count)
return
import unittest
class TestListCounters(unittest.TestCase):
def test_count_unsorted_list_items(self):
D = (
([], []),
([2], [(2,1)]),
([2,2], [(2,2)]),
([2,2,2,2,3,3,5,5], [(2,4), (3,2), (5,2)]),
)
for inp, exp_outp in D:
counts = count_unsorted_list_items(inp)
print inp, exp_outp, counts
self.assertEqual(counts, dict( exp_outp ))
inp, exp_outp = UNSORTED_WIN = ([2,2,4,2], [(2,3), (4,1)])
self.assertEqual(dict( exp_outp ), count_unsorted_list_items(inp) )
def test_count_sorted_list_items(self):
D = (
([], []),
([2], [(2,1)]),
([2,2], [(2,2)]),
([2,2,2,2,3,3,5,5], [(2,4), (3,2), (5,2)]),
)
for inp, exp_outp in D:
counts = list( count_sorted_list_items(inp) )
print inp, exp_outp, counts
self.assertEqual(counts, exp_outp)
inp, exp_outp = UNSORTED_FAIL = ([2,2,4,2], [(2,3), (4,1)])
self.assertEqual(exp_outp, list( count_sorted_list_items(inp) ))
# ... [(2,2), (4,1), (2,1)]
建議使用 numpy 的bincount<\/a> ,但它僅適用於具有非負整數的一維數組<\/em>。 此外,結果數組可能會令人困惑(它包含原始列表中從 min 到 max 的整數的出現,並將缺失的整數設置為 0)。
使用 numpy 執行此操作的更好方法是使用
unique<\/a>函數並將屬性
return_counts<\/code>設置為 True。
它返回一個元組,其中包含唯一值數組和每個唯一值出現的數組。
# a = [1, 1, 0, 2, 1, 0, 3, 3]
a_uniq, counts = np.unique(a, return_counts=True) # array([0, 1, 2, 3]), array([2, 3, 1, 2]
計算具有共同類型的不同元素的數量:
li = ['A0','c5','A8','A2','A5','c2','A3','A9']
print sum(1 for el in li if el[0]=='A' and el[1] in '01234')
您還可以使用內置模塊
operator<\/code><\/a>的
countOf<\/code><\/a>方法。
>>> import operator
>>> operator.countOf([1, 2, 3, 4, 1, 4, 1], 1)
3
我會使用
filter()<\/code> ,以 Lukasz 為例:
>>> lst = [1, 2, 3, 4, 1, 4, 1]
>>> len(filter(lambda x: x==1, lst))
3
使用 %timeit 查看哪個操作更有效。 np.array 計數操作應該更快。
from collections import Counter
mylist = [1,7,7,7,3,9,9,9,7,9,10,0]
types_counts=Counter(mylist)
print(types_counts)
可能不是最有效的,需要額外通過才能刪除重復項。
功能實現:
arr = np.array(['a','a','b','b','b','c'])
print(set(map(lambda x : (x , list(arr).count(x)) , arr)))
給定一個列表 X
import numpy as np
X = [1, -1, 1, -1, 1]
sum([1 for elem in <yourlist> if elem==<your_value>])
這將返回 your_value 的出現次數
或者,您也可以自己實現計數器。 這就是我的做法:
item_list = ['me', 'me', 'you', 'you', 'you', 'they']
occ_dict = {}
for item in item_list:
if item not in occ_dict:
occ_dict[item] = 1
else:
occ_dict[item] +=1
print(occ_dict)
如果您想要特定元素的多次出現:
>>> from collections import Counter
>>> z = ['blue', 'red', 'blue', 'yellow', 'blue', 'red']
>>> single_occurrences = Counter(z)
>>> print(single_occurrences.get("blue"))
3
>>> print(single_occurrences.values())
dict_values([3, 2, 1])
l2=[1,"feto",["feto",1,["feto"]],['feto',[1,2,3,['feto']]]]
count=0
def Test(l):
global count
if len(l)==0:
return count
count=l.count("feto")
for i in l:
if type(i) is list:
count+=Test(i)
return count
print(Test(l2))
mot = ["compte", "france", "zied"]
lst = ["compte", "france", "france", "france", "france"]
dict((x, lst.count(x)) for x in set(mot))
對於本主題,我知道以下六種方法可以計算列表中元素的出現次數:
count()
方法 count()
是內置的 function ,通過它 python 在列表中計數出現。 在所有其他用於計算發生次數的方法中,它是最簡單的。 Count()
方法采用一個參數,即要計算其出現次數的元素。
例如:
sample_list = ["a", "ab", "a", "abc", "ab", "ab"]
print(sample_list.count("a"))
print(sample_list.count("ab"))
Output
2 3
另一種計算發生次數的簡單方法是使用帶有計數器變量的循環。 在這里,計數器變量在遍歷給定元素后每次都會將其值增加一。 最后,計數器變量的值顯示元素出現的次數。
例如:
def countElement(sample_list, element):
return sample_list.count(element)
sample_list = ["a", "ab", "a", "abc", "ab", "ab"]
element = "ab"
print('{} has occurred {} times'.format(element, countElement(sample_list, element)))
Output
ab has occurred 3 times
countof()
方法 python 庫中的操作員模塊由countof()
方法組成,該方法有助於從列表中返回元素的出現次數。 該方法取兩個arguments,即需要進行計數的列表和需要查找的元素。 此外,您必須在開始程序之前使用import
關鍵字導入 operator 模塊,如下所示:
例如:
sample_list = ["a", "ab", "a", "abc", "ab", "ab"]
import operator as op
print(op.countOf(sample_list,"a"))
Output
2
counter()
方法 Python 擁有一個名為 collections 的內置模塊,包括多種方法來簡化您的編程。 一種這樣的方法是counter()
方法,其中元素存儲為帶有鍵的字典,計數作為值。
因此, counter()
方法通過將一個參數作為要計算元素的列表來幫助您返回給定列表中給定元素的出現總數。 請記住,您必須導入 collections 模塊才能使用counter()
方法,如下例所示:
例如:
sample_list = ["a", "ab", "a", "abc", "ab", "ab"]
from collections import Counter
print(Counter(sample_list))
c = Counter(sample_list)
print(c["a"])
Output
Counter({'ab': 3, 'a': 2, 'abc': 1}) 2
pandas
庫Pandas 是內置的 python 庫,在數據分析和數據操作中非常流行。 它是一個具有大量功能的開源工具,廣泛應用於機器學習和人工智能等領域。
Pandas 擁有多種默認方法,其中之一是 value_count() 方法。 與value_count()
方法一起,pandas 使用系列,即軸為 label 的一維數組。
要使用 pandas 計算元素的出現次數,您必須將給定列表轉換為系列,然后使用value_count()
方法,該方法按降序返回 object。 通過這些,您可以很容易地注意到第一個元素始終是最常出現的元素。
查看以下示例以更好地了解 Pandas 庫
例如:
import pandas as pd
sample_list = ["a", "ab", "a", "abc", "ab", "ab"]
count = pd.Series(sample_list).value_counts()
print(count["a"])
Output
2
這是 python 使用循環、條件語句和字典計算列表中出現次數的最傳統方法。 通過這種方法,您必須創建空字典,然后遍歷列表。 稍后,檢查列表中存在的元素是否在字典中可用。 如果是,則將其值加一; 否則,在字典中引入一個新元素並為其賦值 1。 重復相同的過程,直到列表中的所有元素都被訪問。
請記住,此方法與之前使用循環和計數器變量的方法有很大不同。 前面提到的方法沒有使用字典數據結構,而這個方法使用了。 最后,打印每個元素的出現次數,如下例所示:
例如:
sample_list = ["a", "ab", "a", "abc", "ab", "ab"]
def countOccurrence(a):
k = {}
for j in a:
if j in k:
k[j] +=1
else:
k[j] =1
return k
print(countOccurrence(sample_list))
Output
{'a': 2, 'ab': 3, 'abc': 1}
a =[random.randint(0,100) for i in range(100)]
list(zip(set(a),[a.count(i) for i in set(a)]))
test = [409.1, 479.0, 340.0, 282.4, 406.0, 300.0, 374.0, 253.3, 195.1, 269.0, 329.3, 250.7, 250.7, 345.3, 379.3, 275.0, 215.2, 300.0]
for i in test:
print('{} numbers {}'.format(i, test.count(i)))
import pandas as pd
test = [409.1, 479.0, 340.0, 282.4, 406.0, 300.0, 374.0, 253.3, 195.1, 269.0, 329.3, 250.7, 250.7, 345.3, 379.3, 275.0, 215.2, 300.0]
#turning the list into a temporary dataframe
test = pd.DataFrame(test)
#using the very convenient value_counts() function
df_counts = test.value_counts()
df_counts
那么您可以使用df_counts.index
和df_counts.values
來獲取數據。
x = ['Jess', 'Jack', 'Mary', 'Sophia', 'Karen',
'Addison', 'Joseph','Jack', 'Jack', 'Eric', 'Ilona', 'Jason']
the_item = input('Enter the item that you wish to find : ')
how_many_times = 0
for occurrence in x:
if occurrence == the_item :
how_many_times += 1
print('The occurrence of', the_item, 'in', x,'is',how_many_times)
創建了一個名稱列表,其中重復了名稱“Jack”。 為了檢查它的出現,我在名為x
的列表中運行了一個 for 循環。 在每次迭代中,如果循環變量的值與從用戶接收到的值相同並存儲在變量 the_item 中,則變量the_item
會增加 1。在達到某個值how_many_times
how_many_times
發生的值“傑克”這個詞
def countfrequncyinarray(arr1):
r=len(arr1)
return {i:arr1.count(i) for i in range(1,r+1)}
arr1=[4,4,4,4]
a=countfrequncyinarray(arr1)
print(a)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.