[英]How to print with itertools groupby?
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=" ")
Example what I need:例如我需要什么:
A B C
2 2 1
My itertools
only shows like this:我的
itertools
只显示如下:
A 2 B 2 C 1
Using multiple print statements with transpose将多个打印语句与转置一起使用
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=" ")
You can do it like this which post-processes the results groupby
returns to make it easy to get the values needed for each row of the output:您可以这样做,它对结果
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
Here is one more alternative:这是另一种选择:
from 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)
I know you asked about itertools.groupby, BUT I would use a Counter for such task:我知道你问过 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
Since groupby()
does not lend itself to deploying tee()
to make a copy, the best solution seems to be to create a tuple comprehension.由于
groupby()
不适合部署tee()
来制作副本,因此最好的解决方案似乎是创建一个元组理解。 Note that we're not interested in the values contained in each group g, so we'll just store the length of the tuple constructed on the fly from the group.请注意,我们对每个组 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.