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

标签 python

我有一个只有索引的文件 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/

相关文章:

javascript - Session.cookies.get_dict() 返回一个空字典

python - 在 Python Tools for Visual Studio 中调试 GAE

python - 使用 crontab (python) 运行 selenium

c++ - GPL如何影响存储在用户数据中的宏?

python - 如何同时向 Pandas 中的数据框添加多列?

python - numpy 数组中的 ndim 加载了 scipy.io.loadmat?

python - 使用 NLTK,当给出某个单词时,如何生成不同形式的单词?

python - 如何从多个数据帧填充新列?

python - Tkinter 文本小部件比任何其他带有网格的小部件更宽

python - 为什么此解析器找不到使用 namespace 前缀的 XML 标记的内容?