python group by和count每行的列



我有一个文本文件,包含n行,每行有n列,一个分隔符。

File :
x|x|x|x
x|x|x|x|x|x
x|x|x|x|x|x|x|x|x|x|x
x|x|x
x|x|x|x
x|x|x

我想取如下输出

out:

group by Columns(相同列数)-列数-行号

2 - 4 -  line 1, line 5
1 - 6 - line 2
1 - 11 - line 3
2 - 3 - line 4,line 6

你能帮忙吗?我试过用熊猫,但没成功。

当然。你绝对不需要熊猫;collections.defaultdict是你的朋友。

import io
from collections import defaultdict
# Could be a `open(...)` instead, but we're using a
# StringIO to make this a self-contained program.
data = io.StringIO("""
x|x|x|x
x|x|x|x|x|x
x|x|x|x|x|x|x|x|x|x|x
x|x|x
x|x|x|x
x|x|x
""".strip())
linenos_by_count = defaultdict(set)
for lineno, line in enumerate(data, 1):
count = line.count("|") + 1  # Count delimiters, add 1
linenos_by_count[count].add(lineno)
for count, linenos in sorted(linenos_by_count.items()):
lines_desc = ", ".join(f"line {lineno}" for lineno in sorted(linenos))
print(f"{len(linenos)} - {count} - {lines_desc}")

输出
2 - 3 - line 4, line 6
2 - 4 - line 1, line 5
1 - 6 - line 2
1 - 11 - line 3

下面是基于@AKX方法的itertools.groupby的替代方案:

from itertools import groupby
print('n'.join([f'{len(G)} - {k} - '+', '.join([f'line {x[0]+1}' for x in G])
for k, g in groupby(sorted(enumerate([s.count('x')
for s in data.split('n')
]),
key=lambda x: x[1]),
lambda x: x[1]
)
for G in [list(g)]
]))

输出:

2 - 3 - line 4, line 6
2 - 4 - line 1, line 5
1 - 6 - line 2
1 - 11 - line 3

下面是一个不那么野蛮的格式:

from itertools import groupby
counts = [s.count('x') for s in data.split('n')]
for k, g in groupby(sorted(enumerate(counts),
key=lambda x: x[1]),
lambda x: x[1]):
G = list(g)
print(f'{len(G)} - {k} - '+', '.join([f'line {x[0]+1}' for x in G]))

最新更新