2

これをネストされたforループをよりpythonicにする方法を探しています。具体的には、3つの変数の一意の組み合わせを反復処理し、データが辞書に存在する場合はファイルに書き込むにはどうすればよいですか?

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 > 19901990年より前の年を除外する場合、それらがすでに口述に含まれている場合でも)。

于 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 に答える