假设我有一个清单:
a = ['apple', 'carrot']
Run Code Online (Sandbox Code Playgroud)
和字典:
d ={'apple': [2,4], 'carrot': [44,33], 'orange': [345,667]}
Run Code Online (Sandbox Code Playgroud)
如何使用列表a作为在字典d中查找的键?我希望将结果写入以逗号分隔的文本文件中
apple, carrot
2, 44
4, 33
Run Code Online (Sandbox Code Playgroud)
更正了a = ['apple','orange']到a = ['apple','胡萝卜']的a-list
a = ['apple', 'orange']
d ={'apple': [2,4], 'carrot': [44,33], 'orange': [345,667]}
print ',\t'.join(a)
for row in zip(*(d[key] for key in a)):
print ',\t'.join(map(str, row))
Run Code Online (Sandbox Code Playgroud)
输出:
apple, orange
2, 345
4, 667
Run Code Online (Sandbox Code Playgroud)
我知道其他人的速度更快,他们的解决方案也类似,但这是我的看法(接受或保留):
a = ['apple', 'orange']
d ={'apple': [2,4], 'carrot': [44,33], 'orange': [345,667]}
fo = open('test.csv','w')
fo.write(',\t'.join(a)+'\n')
for y in xrange(len(d[a[0]])):
fo.write(',\t'.join([str(d[i][y]) for i in a])+'\n')
fo.close()
Run Code Online (Sandbox Code Playgroud)
它生成文件 test.csv:
apple, orange
2, 345
4, 667
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2007 次 |
| 最近记录: |