python - 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
你能帮我吗?我尝试过使用熊猫,但我无法成功。
解决方案
当然。你绝对不需要 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
推荐阅读
- android - 启用 proguard 时出现错误
- node.js - 我如何使用 Promise.all 使其工作?
- sql - 为了避免在递归 CTE 中使用 2 个 Oracle / SQL 表进行循环引用
- vue.js - Vue Select 或 Vue 多选,如何设置默认值并使其可点击
- java - JAVA_HOME 无效(cordova)错误
- java - 为什么在通过 JSP 将 MultipartFile 图像作为 byte[] 上传到 DB 时需要将 BindingResult 作为方法参数?
- firebase - Firebase signInWithCustomToken 未过期?
- machine-learning - 错误:找到暗淡 3 的数组。预计估计器 <= 2。MLPClassifier
- ios - 无法设置 Datepicker,报错
- reactjs - 使用 reactjs 更改 URL 无限滚动