我正在寻找一些方法来使此嵌套循环更pythonic。具体而言,如何通过三个变量的独特组合迭代,并在数据存在字典中时写入文件?从嵌套for循环写入文件尝试语句
foo,bar = {},{} #filling of dicts not shown
with open(someFile,'w') as aFile:
for year in years:
for state in states:
for county in counties:
try:foo[year,state,county],bar[state,county]
except:continue
aFile.write("content"+"\n")
这可能无法正常工作,如果'years','states'和'counties'序列比'foo'或'bar'的键更受限制。 – Blckknght
@Blckknght:这是真的,但是通过在'if'语句中加入额外的限制,你可以很容易地解决这个问题。我编辑了我的答案。 – BrenBarn
当使用'sorted(foo)'和'sorted(foo.iterkeys())'时,我似乎得到相同的输出。 'sorted(foo.iterkeys())'有什么优势? – metasequoia