【发布时间】:2014-09-17 13:35:49
【问题描述】:
我有两个文件,一个仅包含 Keys,另一个包含 Key and Value。我正在尝试使用相应的值附加密钥文件,或者使用密钥和相应的值创建一个新的输出文件。个人我可以完美地阅读关键和价值。我在将两者合并在一起时遇到了麻烦。它下面的代码一起显示了最终值。我知道第一个 for 循环正在结束,然后第二个 for 循环正在开始。这就是我只从键和值文件中获取最后一项的原因。如何以简单的方式解决这个问题?
from collections import defaultdict
with open('input1', 'r') as classified_data:
with open('input2', 'r') as edge_data:
with open('output', 'w') as outfile:
for row in classified_data:
col = row.strip().split()
key = col[0], col[1]
#print key
for row in edge_data:
col = row.strip().split()
value = col[2], col[3], col[4]
#print value
print {key:value}
输入1:
3545 4945
3545 2814
3545 5045
3545 4921
3545 2564
3545 2311
3545 1644
3545 3820
3545 388
3545 928
3545 3626
3545 1191
3545 4243
3545 3867
3545 701
输入2:
4945 3545 57 250848.0 4400.84210526
3584 292 5 1645.0 329.0
4824 2283 5 16867.0 3373.4
1715 55 1 681.0 681.0
5409 2822 2 3221.0 1610.5
4955 656 6 3348.0 558.0
4157 487 1 201.0 201.0
2628 309 2 2466.0 1233.0
3929 300 2 1742.0 871.0
3730 489 12 10706.0 892.166666667
5474 2336 2 1533.0 766.5
3877 716 10 45028.0 4502.8
3058 3045 12 17328.0 1444.0
【问题讨论】:
-
目前还不清楚如何将第一个文件的行与第二个文件的行关联起来。第一个文件的第 1 行是否与第二个文件的第 1 行相关,依此类推?
-
@goncalopp 不行。我必须使用files2中的密钥对从file1中搜索密钥对,然后从file2中提取相应的值并打印。
标签: python file dictionary key key-value