etc./StackOverFlow

목록 항목의 발생 횟수를 어떻게 계산합니까?

청렴결백한 만능 재주꾼 2022. 1. 2. 04:53
반응형

질문자 :weakish


항목이 주어지면 Python의 목록에서 항목의 발생을 어떻게 계산할 수 있습니까?



하나의 항목만 계산하려면 count 메서드를 사용하세요.

 >>> [1, 2, 3, 4, 1, 4, 1].count(1) 3

카운트 성능에 관한 중요 참고 사항

여러 항목을 계산하려면 이것을 사용하지 마십시오 .

count 를 호출 count 호출에 대해 목록에 대한 별도의 전달이 필요하며, 이는 성능에 치명적일 수 있습니다.

모든 항목을 계산하거나 여러 항목만 계산하려면 다른 답변에 설명된 대로 Counter


Łukasz

Python 2.7 또는 3.x를 사용 중이고 각 요소의 발생 횟수를 원하는 경우 Counter 사용하십시오.

 >>> from collections import Counter >>> z = ['blue', 'red', 'blue', 'yellow', 'blue', 'red'] >>> Counter(z) Counter({'blue': 3, 'red': 2, 'yellow': 1})

user52028778

목록에서 한 항목의 발생 횟수 계산

하나의 목록 항목의 발생 횟수를 계산하려면 count()

 >>> l = ["a","b","b"] >>> l.count("a") 1 >>> l.count("b") 2

목록에 있는 모든 항목의 발생 횟수를 계산하는 것을 목록 "계산" 또는 집계 카운터 생성이라고도 합니다.

count()를 사용하여 모든 항목 계산

l 에서 항목의 발생을 계산하려면 count() 메서드를 사용하면 됩니다.

 [[x,l.count(x)] for x in set(l)]

(또는 유사하게 사전 dict((x,l.count(x)) for x in set(l)) )

예시:

 >>> l = ["a","b","b"] >>> [[x,l.count(x)] for x in set(l)] [['a', 1], ['b', 2]] >>> dict((x,l.count(x)) for x in set(l)) {'a': 1, 'b': 2}

Counter()로 모든 항목 계산하기

collections 라이브러리의 더 빠른 Counter 클래스가 있습니다.

 Counter(l)

예시:

 >>> l = ["a","b","b"] >>> from collections import Counter >>> Counter(l) Counter({'b': 2, 'a': 1})

카운터는 얼마나 빠릅니까?

Counter 가 목록 집계에 얼마나 빠른지 확인했습니다. n 값을 사용하여 두 가지 방법을 모두 시도했는데 Counter 가 약 2의 일정한 요소만큼 더 빠른 것으로 보입니다.

다음은 내가 사용한 스크립트입니다.

 from __future__ import print_function import timeit t1=timeit.Timer('Counter(l)', \ 'import random;import string;from collections import Counter;n=1000;l=[random.choice(string.ascii_letters) for x in range(n)]' ) t2=timeit.Timer('[[x,l.count(x)] for x in set(l)]', 'import random;import string;n=1000;l=[random.choice(string.ascii_letters) for x in range(n)]' ) print("Counter(): ", t1.repeat(repeat=3,number=10000)) print("count(): ", t2.repeat(repeat=3,number=10000)

그리고 출력:

 Counter(): [0.46062711701961234, 0.4022796869976446, 0.3974247490405105] count(): [7.779430688009597, 7.962715800967999, 8.420845870045014]

user2314737

사전에서 각 항목의 발생 횟수를 얻는 또 다른 방법:

 dict((i, a.count(i)) for i in a)

tj80

list.count(x) x 가 목록에 나타나는 횟수를 반환합니다.

참조: http://docs.python.org/tutorial/datastructures.html#more-on-lists


Silfverstrom

항목이 주어지면 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가 있습니다. 목록뿐만 아니라 모든 iterable을 Counter에 덤프할 수 있으며 Counter는 요소 수의 데이터 구조를 유지합니다.

용법:

 >>> from collections import Counter >>> c = Counter(l) >>> c['b'] 4

카운터는 Python 사전을 기반으로 하며 키는 요소이므로 키는 해시 가능해야 합니다. 기본적으로 중복 요소를 허용하는 집합과 같습니다.

collections.Counter 추가 사용법

카운터에서 iterable로 더하거나 뺄 수 있습니다.

 >>> 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는 공통 라이브러리이지만 표준 라이브러리에는 없습니다. 요구 사항으로 추가하는 것은 간단하지 않습니다.

목록 개체 자체와 표준 라이브러리에 이 사용 사례에 대한 내장 솔루션이 있습니다.

프로젝트에 아직 팬더가 필요하지 않은 경우 이 기능만을 위한 요구 사항으로 만드는 것은 어리석은 일입니다.


Aaron Hall

제안된 모든 솔루션(및 몇 가지 새로운 솔루션)을 perfplot(작은 프로젝트 )와 비교했습니다.

하나의 항목 계산

충분히 큰 배열의 경우

 numpy.sum(numpy.array(a) == 1)

다른 솔루션보다 약간 빠릅니다.

여기에 이미지 설명 입력

모든 항목 계산

이전에 확립된 바와 같이 ,

 numpy.bincount(a)

당신이 원하는 것입니다.

여기에 이미지 설명 입력


플롯을 재현하는 코드:

 from collections import Counter from collections import defaultdict import numpy import operator import pandas import perfplot def counter(a): return Counter(a) def count(a): return dict((i, a.count(i)) for i in set(a)) def bincount(a): return numpy.bincount(a) def pandas_value_counts(a): return pandas.Series(a).value_counts() def occur_dict(a): d = {} for i in a: if i in d: d[i] = d[i]+1 else: d[i] = 1 return d def count_unsorted_list_items(items): counts = defaultdict(int) for item in items: counts[item] += 1 return dict(counts) def operator_countof(a): return dict((i, operator.countOf(a, i)) for i in set(a)) perfplot.show( setup=lambda n: list(numpy.random.randint(0, 100, n)), n_range=[2**k for k in range(20)], kernels=[ counter, count, bincount, pandas_value_counts, occur_dict, count_unsorted_list_items, operator_countof ], equality_check=None, logx=True, logy=True, )
 from collections import Counter from collections import defaultdict import numpy import operator import pandas import perfplot def counter(a): return Counter(a) def count(a): return dict((i, a.count(i)) for i in set(a)) def bincount(a): return numpy.bincount(a) def pandas_value_counts(a): return pandas.Series(a).value_counts() def occur_dict(a): d = {} for i in a: if i in d: d[i] = d[i] + 1 else: d[i] = 1 return d def count_unsorted_list_items(items): counts = defaultdict(int) for item in items: counts[item] += 1 return dict(counts) def operator_countof(a): return dict((i, operator.countOf(a, i)) for i in set(a)) b = perfplot.bench( setup=lambda n: list(numpy.random.randint(0, 100, n)), n_range=[2 ** k for k in range(20)], kernels=[ counter, count, bincount, pandas_value_counts, occur_dict, count_unsorted_list_items, operator_countof, ], equality_check=None, ) b.save("out.png") b.show()

Nico Schlömer

한 번에 모든 값 을 계산하려면 다음과 같이 bincount 를 사용하여 매우 빠르게 계산할 수 있습니다.

 import numpy as np a = np.array([1, 2, 3, 4, 1, 4, 1]) np.bincount(a)

주는

 >>> array([0, 3, 1, 1, 2])

flonk

pandas 를 사용할 수 있다면 value_counts 가 구조를 위해 존재합니다.

 >>> 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

빈도에 따라 결과도 자동으로 정렬됩니다.

결과를 목록 목록에 표시하려면 다음과 같이 하십시오.

 >>> pd.Series(a).value_counts().reset_index().values.tolist() [[1, 3], [4, 2], [3, 1], [2, 1]]

Thirupathi Thangavel

판다를 사용하지 않는 이유는 무엇입니까?

 import pandas as pd l = ['a', 'b', 'c', 'd', 'a', 'd', 'a'] # converting the list to a Series and counting the values my_count = pd.Series(l).value_counts() my_count

산출:

 a 3 d 2 b 1 c 1 dtype: int64

특정 요소의 수를 찾고 있다면, A는 시도라고 :

 my_count['a']

산출:

 3

Shoresh

나는 오늘이 문제가 있었고 SO를 확인하기 전에 내 솔루션을 굴렸습니다. 이것:

 dict((i,a.count(i)) for i in a)

큰 목록의 경우 정말 느립니다. 내 솔루션

 def occurDict(items): d = {} for i in items: if i in d: d[i] = d[i]+1 else: d[i] = 1 return d

실제로 적어도 Python 2.7의 경우 Counter 솔루션보다 약간 빠릅니다.


D Blanc

# 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)]

Wes Turner

다음은 세 가지 솔루션입니다.

가장 빠른 방법은 for 루프를 사용하여 Dict에 저장하는 것입니다.

 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

Akash Swain

itertools.groupby() 가 있는 모든 요소의 수

목록에 있는 모든 요소의 수를 얻기 위한 Antoher 가능성은 itertools.groupby() 사용할 수 있습니다.

"중복" 카운트 포함

 from itertools import groupby L = ['a', 'a', 'a', 't', 'q', 'a', 'd', 'a', 'd', 'c'] # Input list counts = [(i, len(list(c))) for i,c in groupby(L)] # Create value-count pairs as list of tuples print(counts)

보고

 [('a', 3), ('t', 1), ('q', 1), ('a', 1), ('d', 1), ('a', 1), ('d', 1), ('c', 1)]

그것이 처음 세 조합 공지 방법 a 다른 기 동안 ', 제 s의 그룹으로 a 목록을 아래로 존재한다. L 이 정렬되지 않았기 때문에 발생합니다. 이것은 그룹이 실제로 분리되어야 하는 경우 때때로 이점이 될 수 있습니다.

고유 개수 포함

고유한 그룹 수를 원하는 경우 입력 목록을 정렬하기만 하면 됩니다.

 counts = [(i, len(list(c))) for i,c in groupby(sorted(L))] print(counts)

보고

 [('a', 5), ('c', 1), ('d', 2), ('q', 1), ('t', 1)]

참고: 고유 카운트를 생성하기 위해 다른 많은 답변이 groupby 솔루션에 비해 더 쉽고 읽기 쉬운 코드를 제공합니다. 그러나 여기에는 중복 카운트 예제와 평행을 이루기 위해 표시됩니다.


Tim Skov Jacobsen

아주 오래된 질문이지만 하나의 라이너를 찾지 못해 하나 만들었습니다.

 # 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}

Harsh Gundecha

numpy의 bincount 를 사용하는 것이 제안 되었지만 음수가 아닌 정수가 있는 1d 배열에서만 작동합니다. 또한 결과 배열은 혼동될 수 있습니다(원래 목록의 최소값에서 최대값까지의 정수를 포함하고 누락된 정수를 0으로 설정함).

numpy로 이를 수행하는 더 좋은 방법은 return_counts 속성이 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]

그런 다음 다음과 같이 페어링할 수 있습니다.

 dict(zip(a_uniq, counts)) # {0: 2, 1: 3, 2: 1, 3: 2}

또한 다른 데이터 유형 및 "2d 목록"과도 작동합니다.

 >>> a = [['a', 'b', 'b', 'b'], ['a', 'c', 'c', 'a']] >>> dict(zip(*np.unique(a, return_counts=True))) {'a': 3, 'b': 3, 'c': 2}

Andreas K.

공통 유형을 갖는 다양한 요소의 수를 계산하려면 다음을 수행합니다.

 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')

준다

3 , 6하지


eyquem

내장 모듈 operator countOf 메서드를 사용할 수도 있습니다.

 >>> import operator >>> operator.countOf([1, 2, 3, 4, 1, 4, 1], 1) 3

vishes_shell

가장 효율적이지 않을 수 있으며 중복을 제거하기 위해 추가 패스가 필요합니다.

기능 구현:

 arr = np.array(['a','a','b','b','b','c']) print(set(map(lambda x : (x , list(arr).count(x)) , arr)))

반환:

 {('c', 1), ('b', 3), ('a', 2)}

또는 dict 반환:

 print(dict(map(lambda x : (x , list(arr).count(x)) , arr)))

반환:

 {'b': 3, 'c': 1, 'a': 2}

blue-sky

나는 filter() 를 사용하고 Lukasz의 예를 들면 다음과 같습니다.

 >>> lst = [1, 2, 3, 4, 1, 4, 1] >>> len(filter(lambda x: x==1, lst)) 3

IPython

주어진 목록 X

 import numpy as np X = [1, -1, 1, -1, 1]

이 목록의 요소에 대한 i: frequency(i)를 보여주는 사전은 다음과 같습니다.

 {i:X.count(i) for i in np.unique(X)}

산출:

 {-1: 2, 1: 3}

Fatemeh Asgarinejad

%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)

Golden Lion

sum([1 for elem in <yourlist> if elem==<your_value>])

이것은 your_value의 발생 횟수를 반환합니다.


whackamadoodle3000

또는 카운터를 직접 구현할 수도 있습니다. 이것이 내가하는 방식입니다.

 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)

출력: {'me': 2, 'you': 3, 'they': 1}


Abel Rodríguez

특정 요소에 대해 여러 번 발생하려면 다음을 수행하십시오.

 >>> 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])

dimension

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))

이것은 목록 목록에 있더라도 목록의 항목을 재귀적으로 계산하거나 검색합니다.


Mohamed Fathallah

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)))

ash

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)

ravi tanwar

출처 : http:www.stackoverflow.com/questions/2600191/how-can-i-count-the-occurrences-of-a-list-item

반응형