2012-12-08 33 views
2

我正在寻找一些方法来使此嵌套循环更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") 

回答

5

你可以只遍历的foo的键,然后检查是否bar有一个相应的键:

for year, state, county in foo: 
    if (state, county) in bar: 
     aFile.write(...) 

这样你避免在任何迭代不会,至少工作foo

这样做的缺点是,您不知道按键的迭代顺序。如果按照排序顺序需要它们,您可以执行for year, state, county in sorted(foo)

正如@Blckknght在评论中指出的那样,这种方法也会一直为每个匹配键写入。如果你想排除一些年/州/县,你可以将其添加到if声明(例如,if (state, county) in bar and year > 1990排除1990年之前的年份,即使它们已经在字典中)。

+0

这可能无法正常工作,如果'years','states'和'counties'序列比'foo'或'bar'的键更受限制。 – Blckknght

+0

@Blckknght:这是真的,但是通过在'if'语句中加入额外的限制,你可以很容易地解决这个问题。我编辑了我的答案。 – BrenBarn

+0

当使用'sorted(foo)'和'sorted(foo.iterkeys())'时,我似乎得到相同的输出。 'sorted(foo.iterkeys())'有什么优势? – metasequoia

2

建议使用itertools.product来生成您将用作键的值。我想在“更容易请求原谅比许可”的风格之外添加了一些改进处理你正在做的:

import itertools 

with open(some_file, "w"): 
    for year, state, county in itertools.product(years, states, counties): 
     try: 
      something_from_foo = foo[(year, state, county)] 
      something_from_bar = bar[(state, count)] 

      # include the write in the try block 
      aFile.write(something_from_foo + something_from_bar) 

     except KeyError: # catch only a specific exception, not all types 
      pass 
+0

+1 itertools.product'避免宽恕>权限方法的有价值建议 – metasequoia