튜플 목록의 그룹화 된 합을 찾아야 할 때 'Counter'메소드와 '+'연산자를 사용해야합니다.
'카운터'는 해시 가능한 개체를 계산하는 데 도움이 되는 하위 클래스입니다. 즉, 호출될 때 자체적으로 (목록, 튜플 등과 같은 반복 가능한) 해시 테이블을 생성합니다.
개수로 0이 아닌 값을 가진 모든 요소에 대해 itertool을 반환합니다.
'+' 연산자는 숫자 값을 추가하거나 문자열을 연결하는 데 사용할 수 있습니다.
아래는 동일한 데모입니다 -
예시
from collections import Counter
my_list_1 = [('Hi', 14), ('there', 16), ('Jane', 28)]
my_list_2 = [('Jane', 12), ('Hi', 4), ('there', 21)]
print("The first list is : ")
print(my_list_1)
print("The second list is : " )
print(my_list_2)
cumulative_val_1 = Counter(dict(my_list_1))
cumulative_val_2 = Counter(dict(my_list_2))
cumulative_val_3 = cumulative_val_1 + cumulative_val_2
my_result = list(cumulative_val_3.items())
print("The grouped summation of list of tuple is : ")
print(my_result) 출력
The first list is :
[('Hi', 14), ('there', 16), ('Jane', 28)]
The second list is :
[('Jane', 12), ('Hi', 4), ('there', 21)]
The grouped summation of list of tuple is :
[('Hi', 18), ('there', 37), ('Jane', 40)] 설명
- 필수 패키지를 가져옵니다.
- 튜플 목록 두 개가 정의되어 콘솔에 표시됩니다.
- 이 두 튜플 목록은 모두 사전으로 변환됩니다.
- '+' 연산자를 사용하여 추가됩니다.
- 이 결과는 사전의 '값'만 사용하여 목록으로 변환됩니다.
- 이 작업의 데이터는 변수에 저장됩니다.
- 이 변수는 콘솔에 표시되는 출력입니다.