python - 根据可迭代对象中的索引列表访问项目

标签 python

我有大约 4000 万行文本要解析,我想将每一行视为一个拆分字符串,然后使用我在方法中生成的数字列表请求多个切片(或下标,无论它们叫​​什么) .

# ...
other_file = open('output.txt','w')
list = [1, 4, 5, 7, ...]
for line in open(input_file):
    other_file.write(line.split(',')[i for i in list])

下标不能使用我已经展示过的这个生成器,但我想向分割线询问其中的多个条目,而不必在每一行中遍历列表。

抱歉,我知道这是一个简单的答案,但我就是想不出来。这么晚了!

最佳答案

CSV 模块可以帮助您

import csv
reader = csv.reader(open(input_file, 'r'))
writer = csv.writer(open(output_file, 'w'))
fields = (1,4,5,7,...)
for row in reader:
    writer.writerow([row[i] for i in fields])

要进一步改进,请使用 context managers 打开文件

关于python - 根据可迭代对象中的索引列表访问项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9679189/

相关文章:

python - Django {% url %} when urls with parameters like : url(r'^foo/<parameter>/$', include(some.urls))

python - 从 os.listdir(path) 获取 WinError 3 或 UnicodeDecodeError

python - appengine ndb 上类图实体的最佳实践

python - Amazon Ubuntu Postgres - 无法连接到本地主机

python - 如何建立与数据库的全局连接?

一段时间后python子进程变得空闲

python - 标记二维数组中的非零邻居值

python - Flask-SQLAlchemy 超时错误

python - Django 通过多个过滤多对多

python - 文件句柄为父进程打开但为每个子进程关闭