使用try语句从嵌套for循环写入文件

时间:2012-12-08 03:12:09

标签: python for-loop iterator

我正在寻找一些方法来使这个嵌套for循环更加pythonic。具体来说,如何迭代三个变量的唯一组合,如果数据存在于字典中,则写入文件?

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")

2 个答案:

答案 0 :(得分: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年之前的年份,即使它们已经在dict中)。

答案 1 :(得分: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