簡體   English   中英

如何使用 itertools groupby 打印?

[英]How to print with itertools groupby?

我有這個代碼:

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

這是另一種選擇:

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)

我知道你問過 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

暫無
暫無

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

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