繁体   English   中英

python分组并计算每行的列数

[英]python group by and count Columns for each line

我有一个 txt 文件,其中包含 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:

按列分组(列数相同) - 列数 - 行号

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

你能帮我吗? 我尝试过熊猫,但我无法成功。

当然。 你绝对不需要 Pandas; 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]))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM