簡體   English   中英

Python在列表中分組

[英]Python grouping by in lists

我在python中有一個這樣的列表:

list1 = [('a', 6.5),('a', 6.5),('a', -6.5),('b', 0.0),('b', 0.0),('b',6.5),('b', -6.5)('b',6.5)]

我需要一個包含以下內容的列表:

[(a,avg(6.5,6.5,-6.5),no.of_occurences_of_a),(b,avg(0.0,6.5,-6.5,6.5),no.of_occurences_of_b)]

[(a,6.5/3,3)(b,6.5/4,4)]

這個怎么做?

您可以使用itertools.groupby

In [19]: list1 = [('a', 6.5),('a', 6.5),('a', -6.5),('b', 0.0),('b', 0.0),('b',6.5),('b', -6.5),('b',6.5)]

In [20]: from itertools import groupby

In [21]: from operator import itemgetter

In [22]: lis=[]

In [23]: for k,v in groupby(list1,key=itemgetter(0)):
    items=[x[1] for x in v]
    lis.append((k, sum(items)/len(items), len(items)))
   ....:     

In [24]: lis
Out[24]: [('a', 2.1666666666666665, 3), ('b', 1.3, 5)]

請注意,如果list未排序,則必須先使用itertools.groupby對其進行排序以獲得所需的結果。

使用collections.defaultdict ,這也適用於未排序的項目:

In [25]: from collections import defaultdict

In [26]: dic=defaultdict(list)

In [27]: for k,v in list1:
   ....:     dic[k].append(v)
   ....:     

In [28]: dic
Out[28]: defaultdict(<type 'list'>, {'a': [6.5, 6.5, -6.5], 'b': [0.0, 0.0, 6.5, -6.5, 6.5]})

In [29]: [(k,sum(v)/len(v),len(v)) for k,v in dic.items()]
Out[29]: [('a', 2.1666666666666665, 3), ('b', 1.3, 5)]

使用itertools.groupby 通常這是單線的,但在您的情況下有點棘手,因為您需要消耗一組兩次才能得出平均值和長度:

list1 = [('a', 6.5), ('a', 6.5), ('a', -6.5), ('b', 0.0),
         ('b', 0.0), ('b', 6.5), ('b', -6.5), ('b',6.5)]

import itertools
import operator

fst = operator.itemgetter(0)
snd = operator.itemgetter(1)
result = []
for grouper, group in itertools.groupby(sorted(list1, key=fst), key=fst):
    items = map(snd, group)
    result.append((grouper, sum(items)/len(items), len(items)))

丑陋的解決方案(格式不符合您的要求):

list1 = [('a', 6.5),('a', 6.5),('a', -6.5),('b', 0.0),('b', 0.0),('b',6.5),('b', -6.5),('b',6.5)]

a_list = []
b_list = []
a = 0
b = 0
for item in list1:
    if 'a' in item:
        a_list.append(item[1])
        a += 1
    if 'b' in item:
        b_list.append(item[1])
        b +=1

#a is now the count of a's
#b is now the count of b's
a_avarage = reduce(lambda x, y: x + y, a_list)
b_avarage = reduce(lambda x, y: x + y, b_list)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM