Python: 用于唯一键值对的 Itertools groupby

Python: Itertools groupby for unique key value pairs

我正在尝试根据列对 csv 文件中的数据进行分组。我试过了:

from itertools import groupby
import csv
with open('path/trial.csv', 'rb') as f:
    reader = csv.reader(f)
    things = list(reader)

for key, group in groupby(things, lambda x: x[0]):
    listOfThings = len(",".join([thing[1] for thing in group]).split(","))
    print key + "," + str(listOfThings)

当第 1 列中的数据按特定顺序排列时,它起作用了。如果它重复,计数就会变得混乱。

A,1
A,2
A,1
B,0
B,8

我明白了

A,3
B,2

A,1
A,2
B,0
B,8
A,1

我明白了

A,2
B,2
A,1

我希望我的脚本同时考虑唯一键和唯一值,并且输出为(只取一次 A,1,尽管它出现了两次):

A,2
B,2

根据 Chad Simmon 的评论,将其更改为:

sortedlist = list(reader)
things= sorted(sortedlist, key=operator.itemgetter(0), reverse=True)

它现在给了我

B,2
A,3

我想要 A,2。

通过做得到它:

from itertools import groupby
import csv, operator, itertools
with open('trial.csv', 'rb') as f:
    reader = csv.reader(f)
    sortedlist = list(reader)
    things= sorted(sortedlist, key=operator.itemgetter(0), reverse=True)
    things.sort()
    things = list(k for k,_ in itertools.groupby(things))

for key, group in groupby(things, lambda x: x[0]):
    listOfThings = len(",".join([thing[1] for thing in group if not thing in things[1]]).split(","))
    print key + "," + str(listOfThings)

我认为 Chad Simmons 的意思是,如果你想确定整个集合上下文中的唯一性,你应该使用 groupby() 以外的东西。但是,我建议您不要使用字典,而是使用 set — which is similar to one — in addition to a subclass of dictionaries called a collections.Counter.

首先构建文件中所有唯一值对的 set,然后构建仅考虑该对第一个值的值的 Counter(您称它们为 )。如果您希望结果有序,您还需要对 Counter 的内容进行排序,因为它在字典中是无序的,如下所示。

from collections import Counter
import csv

with open('trial.csv', 'rb') as f:
    unique_pairs = set((row[0], row[1]) for row in csv.reader(f))
    for key, count in sorted(Counter(pair[0] for pair in unique_pairs).items()):
        print('{},{}'.format(key, count))