简体   繁体   English

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

[英]write to file from nested for loop with try statement

I am seeking some way to make this nested for loop more pythonic. 我正在寻找使此嵌套for循环更具pythonic的方法。 Specifically, how can I iterate through unique combinations of three variables, and write to file if data is present in the dictionary? 具体来说,如果字典中存在数据,我该如何遍历三个变量的唯一组合并写入文件?

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

You could just iterate over the keys of foo and then check if bar has a corresponding key: 您可以迭代foo的键,然后检查bar是否有相应的键:

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

This way you avoid iterating over anything that won't at least work for foo . 这样,您可以避免迭代至少对foo不起作用的任何东西。

The disadvantage to this is that you don't know what order the keys will be iterated in. If you need them in sorted order you could do for year, state, county in sorted(foo) . 这样做的缺点是你不知道密钥的迭代顺序。如果你需要它们按排序顺序,你可以做for year, state, county in sorted(foo)

As @Blckknght pointed out in a comment, this method also will always write for every matching key. 正如@Blckknght在评论中指出的那样,此方法还将始终为每个匹配的键编写。 If you want to exclude some years/states/counties you could add that to the if statement (eg, if (state, county) in bar and year > 1990 to exclude years before 1990, even if they are already in the dict). 如果你想要排除某些年份/州/县,你可以将它添加到if语句中(例如, if (state, county) in bar and year > 1990中排除1990年以前的年份,即使它们已经在dict中)。

The suggestion of using itertools.product to generate the values you'll use as keys has already been made. 使用itertools.product生成您将用作键的值的建议已经完成。 I want to add some improvements in the "easier to ask for forgiveness than permission" style exception handling you're doing: 我想在您正在做的“异常情况下请求宽恕而不是许可”中添加一些改进:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM