programing

목록 항목의 발생 횟수를 계산하려면 어떻게 해야 합니까?

goodjava 2022. 11. 11. 23:35

목록 항목의 발생 횟수를 계산하려면 어떻게 해야 합니까?

Python에서 하나의 아이템을 지정하면 리스트에서 발생하는 아이템을 어떻게 카운트합니까?


관련성이 있지만 다른 문제는 컬렉션 내의 서로 다른요소의 발생 횟수를 카운트하여 사전 또는 목록을 단일 정수 대신 히스토그램 결과로 가져오는 것입니다.이 문제에 대한 자세한 내용은 사전을 사용하여 목록의 항목 수를 세기를 참조하십시오.

수만을 는, 「」를 사용해 .count★★★★

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

중요: 여러 개의 다른 항목을 세는 경우 이 작업은 매우 느립니다.

★★count이 리스트 n★★★★★★★★★★★★★★★★★★★★★*countn는 times를 의미합니다.n * n퍼포먼스에 치명적인 영향을 미칠 수 있습니다.

여러 항목을 카운트하려면 를 사용하십시오.n합계수표

Python 2.7 또는 3.x를 사용하는 경우 각 요소의 발생 횟수를 원하는 경우 사용합니다.

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

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

는, 「」를 사용할 수 .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()를 사용하여 모든 항목 카운트

아니면, 더 빠른 방법이 있습니다.Countercollections

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]

사전에서 각 항목의 발생 횟수를 가져오는 다른 방법:

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

그리고 수집품도 있습니다.계산대.목록뿐만 아니라 반복 가능한 모든 항목을 카운터에 덤프할 수 있으며, 카운터는 요소의 카운트 데이터 구조를 유지합니다.

사용방법:

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

바보 같은 대답, sum

적절한 답변이 포함되어 있지만 이 예는 약간 유익합니다.가 c라는 합니다.'b':

>>> sum(c == 'b' for c in l)
4

, 가 「」인 , 「」의 한 수를 가 있는 는, 「」로 합니다.True하게 잘 . 부울값의 합계가 되다.True 1.

왜 팬더는 안 돼?

또 다른 답변은 다음과 같습니다.

왜 팬더를 사용하지 않는가?

판다는 흔한 도서관이지만 일반 도서관에는 없어요.요건으로 추가하는 것은 간단하지 않습니다.

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

당신의 프로젝트에 팬더가 아직 필요하지 않다면, 이 기능만을 위해 그것을 요구하는 것은 어리석은 일입니다.

list.count(x)회수를 반환합니다.x

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

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

1개 항목 카운트

충분히 큰 어레이의 경우

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

모든 값을 동시에 계산하려면 numpy 어레이와bincount과 같이

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

그러면

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

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

왜 팬더를 이용하지 않는가?

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

출력:

a    3
d    2
b    1
c    1
dtype: int64

특정 요소의 카운트를 찾고 있는 경우는, 예를 들면 다음과 같이 해 주세요.

my_count['a']

출력:

3

오늘 이 문제가 발생하여 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 솔루션보다 조금 더 빠릅니다.

다음을 포함한 모든 요소 수itertools.groupby()

모든 수 있는 앙투아헤르의 은 스스의의 herherher herher herher herherherher herherher herher herher herher herher 의her anto antoher anto anto anto anto anto anto anto anto anto anto anto anto anto anto anto anto anto anto anto anto anto anto anto anto anto anto anto anto anto anto anto anto anto anto anto anto anto 。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를 첫 번째 그룹으로 하고 다른 그룹에서는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솔루션.그러나 여기에서는 중복 카운트 예시와 병렬을 그리기 위해 보여집니다.

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

매우 오래된 질문이지만, 라이너를 한 개도 찾지 못했기 때문에, 저는 라이너를 하나 만들었습니다.

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

3가지 솔루션은 다음과 같습니다.

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

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

numpy를 사용하는 더 좋은 방법은 속성과 함께 고유한 함수를 사용하는 것입니다.return_countsTrue로 설정합니다.고유값 배열과 각 고유값 배열이 포함된 튜플을 반환합니다.

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

공통 유형을 가진 다양한 요소의 수를 카운트하려면:

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이 아니다

내장 모듈 방식도 사용할 수 있습니다.

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

나는 사용할 것이다.filter()루카시

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

목록 X가 지정됨

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

이 목록의 요소에 대한 i: 빈도(i)를 나타내는 사전은 다음과 같습니다.

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

출력:

{-1: 2, 1: 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)))

반환:

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

'돌아오다'로 반환한다.dict:

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

반환:

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

또는 카운터를 직접 실장할 수도 있습니다.저는 이렇게 하고 있습니다.

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}

mot = ["compte", "france", "zied"]
lst = ["compte", "france", "france", "france", "france"]
dict((x, lst.count(x)) for x in set(mot))

이것은 준다

{'compte': 1, 'france': 4, 'zied': 0}
sum([1 for elem in <yourlist> if elem==<your_value>])

그러면 your_value 발생량이 반환됩니다.

특정 요소에 대해 여러 번 발생하는 경우:

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

잭이라고 합니다.오카렌스를 ''의 '오카렌스' 목록에서 '를했습니다.x마다 루프 한 값을 되는 the_item "display",how_many_times11이 '어디로 가는지'합니다.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)

언급URL : https://stackoverflow.com/questions/2600191/how-do-i-count-the-occurrences-of-a-list-item