Python 2.x: 튜플 목록의 항목 합계 (Python 2.x: Summing items in a list of tuples)


문제 설명

Python 2.x: 튜플 목록의 항목 합계 (Python 2.x: Summing items in a list of tuples)

요약을 위해 목록의 여러 항목이 동일한 첫 번째 변수를 갖는 튜플 목록을 만들었습니다. 예:

    x = [('m32',[1,2,3]),('m32',[2,3,4]),('m32',[4,5,6]),('m33',[1,2,3]),('m33',[2,3,4]),('m33',[4,5,6]),('m34',[1,2,3]),('m34',[2,3,4]),('m34',[4,5,6])....]

튜플에 있는 두 번째 항목의 개별 값(예: 1+2+4, 2+3+5, 3+4+6)을 포함하는 모든 값에 대해 동일한 첫 번째 항목(예: 'm32').

즉, 'm32' 레이블이 지정된 모든 항목에 대해 다른 값을 추가할 수 있기를 원합니다.

어떻게 나는 이것을 슬라이스/인덱싱하여 반복하고 합계를 수행합니까?


참조 솔루션

방법 1:

Some tricky zip magic, along with itertools.groupby to group the matching first items together:

>>> x = [('m32',[1,2,3]),('m32',[2,3,4]),('m32',[4,5,6]),('m33',[1,2,3]),('m33',[2,3,4]),('m33',[4,5,6]),('m34',[1,2,3]),('m34',[2,3,4]),('m34',[4,5,6])]
>>> from itertools import groupby
>>> from operator import itemgetter
>>> for k,g in groupby(x,key=itemgetter(0)):
...  print (k,[sum(i) for i in zip(*zip(*g)[1])])
...
('m32', [7, 10, 13])
('m33', [7, 10, 13])
('m34', [7, 10, 13])

A breakdown of how it works:

g is the group of items with matching keys. zip(*g) transposes the matrix, bringing the keys and values together:

>>> for k,g in groupby(x,key=itemgetter(0)):
...  print zip(*g)
...
[('m32', 'm32', 'm32'), ([1, 2, 3], [2, 3, 4], [4, 5, 6])]
[('m33', 'm33', 'm33'), ([1, 2, 3], [2, 3, 4], [4, 5, 6])]
[('m34', 'm34', 'm34'), ([1, 2, 3], [2, 3, 4], [4, 5, 6])]

Getting the 2nd items:

>>> for k,g in groupby(x,key=itemgetter(0)):
...  print zip(*g)[1]
...
([1, 2, 3], [2, 3, 4], [4, 5, 6])
([1, 2, 3], [2, 3, 4], [4, 5, 6])
([1, 2, 3], [2, 3, 4], [4, 5, 6])

Transposing again to match up the items to sum:

>>> for k,g in groupby(x,key=itemgetter(0)):
...  print zip(*zip(*g)[1])
...
[(1, 2, 4), (2, 3, 5), (3, 4, 6)]
[(1, 2, 4), (2, 3, 5), (3, 4, 6)]
[(1, 2, 4), (2, 3, 5), (3, 4, 6)]

And adding them up:

>>> for k,g in groupby(x,key=itemgetter(0)):
...  print [sum(i) for i in zip(*zip(*g)[1])]
...
[7, 10, 13]
[7, 10, 13]
[7, 10, 13]

방법 2:

The answer given by Mark is great, and probably much more efficient that the one I'll post you. But I still want to post my answer because you are probably new to python and it will be easy for you to understand it.

For this kind of scripts you only need some imagination and basic python notions:

dictionary={}
for name, numbers in x:
    if name in dictionary:
        current_list=dictionary[name]

        for i in range(3):
            current_list[i]+=numbers[i]

    else:
        dictionary[name]=numbers

print(dictionary)

Note that the output is a dictionary: {'m32': [7, 10, 13], 'm33': [7, 10, 13]}..

I hope it help you!

(by catalyst123Mark Tolonenuser3672754)

참조 문서

  1. Python 2.x: Summing items in a list of tuples (CC BY‑SA 2.5/3.0/4.0)

#list #indexing #python-2.7 #slice #tuples






관련 질문

파이썬에서 데이터를 정렬하는 방법 (How arrange data in python)

포스트백 후 모든 항목이 손실되는 CheckBoxList 컨트롤 (CheckBoxList control losing all items after post back)

목록 목록의 효과적인 구현 (Effective implementation of list of lists)

DictReader가 내 파일의 두 줄을 건너뛰고 있습니까? (DictReader is skipping two lines of my file?)

잘못된 값을 얻는 목록 확인 후 (After list checking getting wrong value)

결과를 세로 방향으로 저장하는 방법 (How do i save the result in a Vertical direction)

Python 2.x: 튜플 목록의 항목 합계 (Python 2.x: Summing items in a list of tuples)

itemgetter를 사용하지 않고 n번 발생하는 요소가 있는 목록 내 항목 인쇄 (Printing items inside a list which have an element that occurs n times without using itemgetter)

반환된 목록에서 장소가 바뀐 항목 삭제 (Deleting items that have the place swapped around in a returned list)

arrayToList가 홀수 출력을 생성합니다. 뭐가 문제 야? (arrayToList producing odd outputs. What's wrong?)

R 목록을 벡터로 바꾸는 방법과 목록이 필요한 이유 (R how to turn lists to vectors, and why a list at all)

python, 출력으로 코딩하는 동안 pycharm에서 이 메시지를 받았습니다. :TypeError: can't convert type 'list' to numerator/denominator (python , I got this message in pycharm while coding as output :TypeError: can't convert type 'list' to numerator/denominator)







코멘트