산업 제조
산업용 사물 인터넷 | 산업자재 | 장비 유지 보수 및 수리 | 산업 프로그래밍 |
home  MfgRobots >> 산업 제조 >  >> Industrial programming >> python

예제가 있는 컬렉션의 Python 카운터

파이썬 카운터란 무엇입니까?

Python 카운터는 컨테이너에 있는 각 요소의 수를 보유하는 컨테이너입니다. 카운터는 사전 클래스 내에서 사용 가능한 하위 클래스입니다.

카운터는 사전 클래스 내에서 사용 가능한 하위 클래스입니다. Python 카운터 도구를 사용하여 해시 테이블 개체라고도 하는 개체의 키-값 쌍을 계산할 수 있습니다.

파이썬 카운터를 사용하는 이유

다음은 Python 3 카운터를 사용하는 주요 이유입니다.

이 Python 자습서에서는 다음을 배우게 됩니다.

파이썬 카운터 소개

Python Counter는 모두 반복 가능한 객체인 목록, 튜플, 사전, 문자열을 입력으로 받아 각 요소의 개수를 포함하는 출력을 제공합니다.

구문:

Counter(list)

다음 목록이 있다고 가정해 보십시오.

list1 = ['x','y','z','x','x','x','y', 'z']

목록에는 요소 x, y 및 z가 있습니다. 이 목록에서 Counter를 사용하면 x, y 및 z가 몇 번 있는지 계산합니다. list1에서 counter를 사용하는 경우 출력은 다음과 같아야 합니다.

Counter({'x': 4, 'y': 2, 'z': 2})

따라서 x의 개수는 4, y는 2, z는 2입니다.

Counter를 사용하려면 아래 주어진 예제와 같이 먼저 가져와야 합니다.

from collections import Counter

다음은 Counter 모듈의 작동을 보여주는 간단한 예입니다.

from collections import Counter
list1 = ['x','y','z','x','x','x','y', 'z']
print(Counter(list1))

출력:

Counter({'x': 4, 'y': 2, 'z': 2})

문자열이 있는 카운터

파이썬에서는 모든 것이 객체이고 문자열도 객체입니다. 파이썬 문자열은 단순히 큰따옴표로 문자를 둘러싸서 생성할 수 있습니다. Python은 문자 유형을 지원하지 않습니다. 이들은 길이가 1인 문자열로 처리되며 하위 문자열로도 간주됩니다.

아래 예에서는 문자열이 Counter에 전달됩니다. 키가 요소이고 값이 개수인 키/값 쌍이 있는 사전 형식을 반환합니다. 또한 공백을 요소로 간주하고 문자열의 공백 수를 제공합니다.

예:

from collections import Counter
my_str = "Welcome to Guru99 Tutorials!"
print(Counter(my_str))

출력:

Counter({'o': 3, ' ': 3, 'u': 3, 'e': 2, 'l': 2, 't': 2, 'r': 2, '9': 2, 'W': 1,
 'c': 1, 'm': 1, 'G': 1, 'T': 1, 'i': 1, 'a': 1, 's': 1, '!': 1})

목록이 있는 카운터

목록은 대괄호 안에 요소가 있는 반복 가능한 개체입니다.

목록의 요소는 카운터에 제공될 때 해시 테이블 개체로 변환됩니다. 여기서 요소는 키가 되고 값은 주어진 목록의 요소 개수가 됩니다.

예를 들어 ['x','y','z','x','x','x','y','z']. 목록에 카운터를 제공하면 목록의 각 요소 수를 알려줍니다.

from collections import Counter
list1 = ['x','y','z','x','x','x','y','z']
print(Counter(list1))

출력:

Counter({'x': 4, 'y': 2, 'z': 2})

사전 카운터

사전에는 키/값 쌍으로 요소가 있으며 중괄호 안에 기록됩니다.

사전이 카운터에 제공되면 요소가 키가 되는 해시 테이블 개체로 변환되고 값은 주어진 사전의 요소 개수가 됩니다.

예:{'x':4, 'y':2, 'z':2, 'z':2}. Counter 함수는 주어진 사전에 있는 각 키의 개수를 찾으려고 시도합니다.

from collections import Counter
dict1 =  {'x': 4, 'y': 2, 'z': 2, 'z': 2}
print(Counter(dict1))

출력:

Counter({'x': 4, 'y': 2, 'z': 2})

튜플을 사용한 카운터

튜플은 둥근 ​​괄호 안에 쉼표로 구분된 개체 모음입니다. Counter는 주어진 튜플의 각 요소 수를 알려줍니다.

튜플이 Counter에 주어지면 요소가 키가 되고 값이 주어진 튜플의 요소 개수가 되는 해시 테이블 개체로 변환됩니다.

from collections import Counter
tuple1 = ('x','y','z','x','x','x','y','z')
print(Counter(tuple1))

출력:

Counter({'x': 4, 'y': 2, 'z': 2})

카운터 액세스, 초기화 및 업데이트

카운터 초기화

카운터는 아래와 같이 문자열 값, 목록, 사전 또는 튜플을 전달하여 초기화할 수 있습니다.

from collections import Counter
print(Counter("Welcome to Guru99 Tutorials!"))   #using string
print(Counter(['x','y','z','x','x','x','y', 'z'])) #using list
print(Counter({'x': 4, 'y': 2, 'z': 2})) #using dictionary
print(Counter(('x','y','z','x','x','x','y', 'z'))) #using tuple

아래와 같이 빈 카운터를 초기화할 수도 있습니다.

from collections import Counter
_count = Counter()

카운터 업데이트

update() 메서드를 사용하여 카운터에 값을 추가할 수 있습니다.

_count.update('Welcome to Guru99 Tutorials!')

최종 코드는 다음과 같습니다.

from collections import Counter
_count = Counter()
_count.update('Welcome to Guru99 Tutorials!')
print(_count)

출력은 다음과 같습니다.

Counter({'o': 3, ' ': 3, 'u': 3, 'e': 2, 'l': 2, 't': 2, 'r': 2, '9': 2, 'W': 1,
 'c': 1, 'm': 1, 'G': 1, 'T': 1, 'i': 1, 'a': 1, 's': 1, '!': 1})

카운터 액세스

카운터에서 값을 가져오려면 다음과 같이 하면 됩니다.

from collections import Counter

_count = Counter()
_count.update('Welcome to Guru99 Tutorials!')
print('%s : %d' % ('u', _count['u']))
print('\n')
for char in 'Guru':
    print('%s : %d' % (char, _count[char]))

출력:

u : 3

G : 1
u : 3
r : 2
u : 3

카운터에서 요소 삭제

Counter에서 요소를 삭제하려면 아래 예와 같이 del 을 사용할 수 있습니다.

예:

from collections import Counter
dict1 =  {'x': 4, 'y': 2, 'z': 2}
del dict1["x"]
print(Counter(dict1))

출력:

Counter({'y': 2, 'z': 2})

Python Counter에서의 산술 연산

덧셈, 뺄셈, 교집합 및 합집합과 같은 산술 연산은 아래 예와 같이 카운터에서 수행할 수 있습니다.

예:

from collections import Counter
counter1 =  Counter({'x': 4, 'y': 2, 'z': -2})

counter2 = Counter({'x1': -12, 'y': 5, 'z':4 })

#Addition
counter3 = counter1 + counter2 # only the values that are positive will be returned.

print(counter3)

#Subtraction
counter4 = counter1 - counter2 # all -ve numbers are excluded.For example z will be z = -2-4=-6, since it is -ve value it is not shown in the output

print(counter4)

#Intersection
counter5 = counter1 & counter2 # it will give all common positive minimum values from counter1 and counter2

print(counter5)

#Union
counter6 = counter1 | counter2 # it will give positive max values from counter1 and counter2

print(counter6)

출력:

Counter({'y': 7, 'x': 4, 'z': 2})
Counter({'x1': 12, 'x': 4})
Counter({'y': 2})
Counter({'y': 5, 'x': 4, 'z': 4})

Python Counter에서 사용 가능한 메소드

Counter에서 사용할 수 있는 몇 가지 중요한 방법이 있습니다. 다음은 동일한 목록입니다.

예:요소()

from collections import Counter
counter1 =  Counter({'x': 5, 'y': 2, 'z': -2, 'x1':0})

_elements = counter1.elements() # will give you all elements with positive value and count>0
for a in _elements:
    print(a)

출력:

x
x
x
x
x
y
y

예:most_common(값)

from collections import Counter
counter1 =  Counter({'x': 5, 'y': 12, 'z': -2, 'x1':0})

common_element = counter1.most_common(2) # The dictionary will be sorted as per the most common element first followed by next.
print(common_element)

common_element1 = counter1.most_common() # if the value is not given to most_common , it will sort the dictionary and give the most common elements from the start.The last element will be the least common element.
print(common_element1)

출력:

 [('y', 12), ('x', 5)]
[('y', 12), ('x', 5), ('x1', 0), ('z', -2)]

예:빼기()

from collections import Counter
counter1 =  Counter({'x': 5, 'y': 12, 'z': -2, 'x1':0})
counter2 = Counter({'x': 2, 'y':5})

counter1.subtract(counter2)
print(counter1)

출력:

Counter({'y': 7, 'x': 3, 'x1': 0, 'z': -2})

예:업데이트()

from collections import Counter
counter1 =  Counter({'x': 5, 'y': 12, 'z': -2, 'x1':0})
counter2 = Counter({'x': 2, 'y':5})
counter1.update(counter2)
print(counter1)

출력:

Counter({'y': 17, 'x': 7, 'x1': 0, 'z': -2})

Python에서 카운트 재할당

아래와 같이 카운터 개수를 다시 할당할 수 있습니다.

다음과 같은 사전이 있다고 가정합니다. {'x':5, 'y':12, 'z':-2, 'x1':0}

아래와 같이 요소 수를 변경할 수 있습니다.

from collections import Counter
counter1 =  Counter({'x': 5, 'y': 12, 'z': -2, 'x1':0})

counter1['y'] = 20

print(counter1)

출력:실행 후 y 개수가 12에서 20으로 변경된 것을 볼 수 있습니다.

Counter({'y': 20, 'x': 5, 'x1': 0, 'z': -2})

카운터를 사용하여 요소 수 가져오기 및 설정

Counter를 사용하여 요소 수를 얻으려면 다음과 같이 하면 됩니다.

from collections import Counter
counter1 =  Counter({'x': 5, 'y': 12, 'z': -2, 'x1':0})
print(counter1['y']) # this will give you the count of element 'y'

출력:

12

요소 수를 설정하려면 다음과 같이 할 수 있습니다.

from collections import Counter
counter1 =  Counter({'x': 5, 'y': 12, 'z': -2, 'x1':0})

print(counter1['y'])

counter1['y'] = 20
counter1['y1'] = 10

print(counter1)

출력:

12
Counter({'y': 20, 'y1': 10, 'x': 5, 'x1': 0, 'z': -2})

요약:


python

  1. EXAMPLE이 있는 Python String strip() 함수
  2. 예제가 있는 Python 문자열 count()
  3. Python String format() 예제로 설명
  4. 파이썬 문자열 길이 | len() 메서드 예제
  5. 예제가 있는 Python 문자열 find() 메서드
  6. 예제가 있는 Python Lambda 함수
  7. 예제가 있는 Python round() 함수
  8. 예제가 있는 Python map() 함수
  9. 예제가 있는 Python Timeit()
  10. 예제가 있는 Python 목록 count()