首页 > 解决方案 > python分组并计算每行的列

问题描述

我有一个 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

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

标签: pythonpandas

解决方案


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

推荐阅读