1

例:

complete_dict = dict()
common_set = set()
for count, group_name in enumerate(groups_dict):
    complete_dict[group_name] = dict()  # grabs a json file = group_name.json

    if count > 0:
        common_set.intersection_update(complete_dict[group_name])
    else:
        # this accounts for the fact common_set is EMPTY to begin with
        common_set.update(complete_dict[group_name])

WHERE: dict2(グループの) メンバーの k:v を含む: int(x)

交差点の初期状態を処理するより適切な方法はありますか?

つまり、最初のものは空であり、したがって結果complete_dict[group_name]空であるため、最初のものと交差することはできません。common_set

4

3 に答える 3

2

特殊なケースを回避する 1 つの方法は、アイテムの内容でセットを初期化することです。それ自体と交差する値は値そのものなので、この方法で何も失うことはありません。

これがどのように機能するかを示す試みを次に示します。さまざまな呼び出しが何を表しているのかを理解しているかどうかはわかりませdict(...)ん。そのため、これはコードに完全に変換されない可能性がありますが、正しい道に進むはずです.

it = iter(dict(...)) # this is the dict(...) from the for statement
first_key = next(it)
results[first_key] = dict(...) # this is the dict(...) from inside the loop

common = set(results[first_key]) # initialize the set with the first item

for key in it:
    results[key] = dict(...) # the inner dict(...) again
    common.intersection_update(result[key])

jamylak がコメントしたように、keysさまざまな辞書のメソッドに対して行っていた呼び出しは常に不要でした (setインデックスを作成したり、マッピング固有のメソッドを使用したりしない場合、辞書はキーのように機能します)。また、Python のスタイルにより適した変数を選択しました (lowercase通常の変数の場合CAPITALSは定数用に予約済み)。

于 2013-04-25T11:46:44.607 に答える
1

Blcknghtの答えに従いますが、複雑さと繰り返しは少なくなります:

common = None
uncommon = {}

for key in outer_dict:
    inner = uncommon[key] = inner_dict(...)
    if common is None:
        common = set(inner)
    else:
        common.intersection_update(inner)

Blcknght のように、変数名が説明的でも明確でもないため、これが元の意図を捉えているかどうかを知るのは困難です。

于 2013-04-25T12:43:46.937 に答える