【问题标题】:write to file from nested for loop with try statement使用 try 语句从嵌套的 for 循环写入文件
【发布时间】:2012-11-26 06:42:50
【问题描述】:

我正在寻找一些方法来让这个嵌套的 for 循环更符合 Python 风格。具体来说,如果字典中存在数据,我如何遍历三个变量的唯一组合,并写入文件?

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

【问题讨论】:

    标签: python for-loop iterator


    【解决方案1】:

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

    【讨论】:

    • 如果years、states 和counties 序列比foo 或bar 的键更受限制,这可能无法正常工作。
    • @Blckknght:确实如此,但是您可以通过在if 语句中设置额外的限制来轻松解决这个问题。我编辑了我的答案。
    • 我在使用sorted(foo) 和sorted(foo.iterkeys()) 时似乎得到了相同的输出。 sorted(foo.iterkeys())有什么优势?
    • @metasequoia:对不起,我只是习惯使用iterkeys 来表明我正在使用密钥。你也可以使用sorted(foo)。
    【解决方案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
    

    【讨论】:

    • +1 对itertools.product 的宝贵建议以避免宽恕> 许可方法
    猜你喜欢
    • 2018-06-06
    • 1970-01-01
    • 2015-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-05
    • 2019-04-22
    • 1970-01-01
    相关资源
    最近更新 更多