gpt4 book ai didi

python - 如何仅使用 file1 中的索引从 file2 获取值(行)?

转载 作者:太空宇宙 更新时间:2023-11-03 19:31:54 24 4
gpt4 key购买 nike

我有一个只有索引的文件 1,第二个文件 2 包含文件 1 的这些索引的值。如何使用 file1 中的索引从 file2 获取这些值,并将其值输出到第三个文件。为简单起见,file1 中的每个索引在 file2 中都有其关联的值。

例如:

文件1:

2
3
4

文件2内容:

0.24  0.43             
0.34 0.28
7.50 0.67
0.23 0.78
0.45 0.49

预期结果

7.50 0.67
0.23 0.78
0.45 0.49

file1 #仅包含索引file2 #file1 中的每个索引都包含具有关联索引的值

fname = file1.readlines()
fname2 = file2.readlines()
outfile = open('Values.txt','w')

for index in fname:
for line in fname2:
if line == index:
outfile.writelines(line)

print "all indices' values have been written to a file success

最佳答案

这些解决方案不依赖于 file1 的排序,但它们确实将 file2 加载到内存中,如果 file2 很大,这可能会导致成本高昂。但是您会注意到,第一个示例中的wanted_lines和lines_out是生成器,这应该节省少量的内存。

这个示例没有错误处理,但基本上是您所需要的。我很快就会拼出一个更好的。

wanted_lines = (int(line) for line in open(file1).readlines())
all_lines = [line.strip() for line in open(file1).readlines()]
lines_out = (all_lines[index] for index in wanted_lines)
open(file3, 'w').writelines(lines_out)
<小时/>

更好:

all_lines = [line.strip() for line in open(file2).readlines()]
lines_out = []
for line in open(file1).readlines():
try:
index = int(line)
lines_out.append(all_lines[index] + '\n')
except IndexError:
print file1, "is only", len(file1), "lines long, therefore has no", index+1, "th line."
except:
print "could not coerce", line.strip(), "to an int"
open(file3, 'w').writelines(lines_out)

关于python - 如何仅使用 file1 中的索引从 file2 获取值(行)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5393150/

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