gpt4 book ai didi

python - 使用列表在文件中压缩行并迭代

转载 作者:太空宇宙 更新时间:2023-11-03 11:51:56 25 4
gpt4 key购买 nike

我想创建一个字典,其中的键取自 keys 列表,值是取自多个文本文件的行列表。假设列表 keys 和所有要读取的文件具有相同的行数。

如何同时遍历列表 keys 和每个文件的行?我的想法是使用 zip() 但这对我不起作用。

我知道我可以使用以下方法遍历文件中的行:

currFile = open('myfile.txt', 'r')
for line in currFile:
# Do something

我知道我可以同时迭代两个列表:

for foo, bar in zip(foos, bars):
# Do something

但这行不通:

myDict = {}
keys = [17, 21, 8, 2, ..., 91]
currFile = open('myfile.txt', 'r')
for key, line in zip(keys, currFile):
myDict[key] = line

我可以将文件中的所有行拉出到一个列表中,压缩它,然后运行循环,但这不会很有效。

如何同时遍历列表 keys 和文件中的行,以便动态调用 zip()?

最佳答案

want to create a dictionary where the keys are line numbers and the values are lists of lines taken from multiple text files. Let's assume all the files to be read have the same number of lines.

这个解决方案适用于任意数量的文件,这个演示只有两个。演示文件 file1 的内容:

line0
line1
line2
line3

演示文件 file2 的内容:

line5
line6
line7
line8

现在列出您的文件对象 files(例如 [open('file1','r'), open('file2','r')]).

from collections import defaultdict as ddict
d = ddict(list)
for number,lines in enumerate(zip(*files)):
for line in lines:
d[number].append(line)

我使用 Python3,如果您使用 Python2.x,请使用 izip。关闭文件:

for file in files:
file.close()

d的内容:

defaultdict(<type 'list'>, {0: ['line0\n', 'line5\n'], 1: ['line1\n', 'line6\n'], 2: ['line2\n', 'line7\n'], 3: ['line3\n', 'line8\n']})

关于python - 使用列表在文件中压缩行并迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24498526/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com