2

我正在寻找某种方法来使这个嵌套的 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")
4

2 回答 2

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 年之前的年份,即使它们已经在字典中)。

于 2012-12-08T03:17:36.617 回答
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
于 2012-12-08T03:28:26.723 回答