I have this code:
from itertools import groupby
text = ["a", "a", "b", "b", "c"]
group = groupby(text)
for k, g in group:
print(k, end= " ")
print(sum(1 for _ in g), end=" ")
我需要的例子:
A B C
2 2 1
我的 itertools
只显示如下:
A 2 B 2 C 1
I have this code:
from itertools import groupby
text = ["a", "a", "b", "b", "c"]
group = groupby(text)
for k, g in group:
print(k, end= " ")
print(sum(1 for _ in g), end=" ")
我需要的例子:
A B C
2 2 1
我的 itertools
只显示如下:
A 2 B 2 C 1
使用多个打印语句与转置一起使用
from itertools import groupby
text = ["a", "a", "b", "b", "c"]
group = groupby(text)
# Transpose so we have row 0 with group names, and row 1 with grouping items
transposed = [(k, list(g)) for k, g in group]
for k in transposed:
print(k[0], end = " ")
print()
for k in transposed:
print(sum(1 for _ in k[1]), end=" ")
groupby
返回的结果进行后处理,以便轻松获取输出每一行所需的值。from itertools import groupby
text = ["a", "a", "b", "b", "c"]
groups = [(k, str(sum(1 for _ in g))) for k, g in groupby(text)]
a, b = zip(*groups)
print(' '.join(a)) # -> a b c
print(' '.join(b)) # -> 2 2 1
zip(*groups)
看起来很美。 - j1-leezip()
也可以解压缩。 - martineaufrom itertools import groupby
text = ["a", "a", "b", "b", "c"]
group = groupby(text)
dictionary = {}
for k, g in group:
dictionary[k] = sum(1 for _ in g)
keys = " ".join(list(dictionary.keys()))
values = " ".join(str(v) for v in list(dictionary.values()))
print(keys)
print(values)
我知道你问的是itertools.groupby,但是我会使用Counter来完成这样的任务:
>>> text = ["a", "a", "b", "b", "c"]
>>> from collections import Counter
>>> c = Counter(text)
>>> print(c)
Counter({'a': 2, 'b': 2, 'c': 1})
>>> headers = c.keys()
>>> values = [str(val) for val in c.values()]
>>> print(' '.join(headers))
a b c
>>> print(' '.join(values))
2 2 1
由于groupby()
方法并不适合使用tee()
来进行复制,因此最好的解决方案似乎是创建一个元组推导式。请注意,我们并不关心每个分组g中包含的值,因此我们只需存储从组中实时构建的元组的长度。
import itertools
text = ["a", "a", "b", "b", "c"]
group = tuple((k,len(tuple(v))) for k,v in itertools.groupby(text))
for t in group:
print(t[0], end= " ")
print()
for t in group:
print(t[1], end=" ")
print()
# a b c
# 2 2 1