7

Pythonで(リスト内包表記を使用せずに) 2つのリストを反復処理する賢い方法はありますか?

つまり、次のようなものです。

# (a, b) is the cartesian product between the two lists' elements
for a, b in list1, list2:
   foo(a, b)

それ以外の:

for a in list1:
    for b in list2:
        foo(a, b)
4

3 に答える 3

13

itertools.product()まさにこれを行います:

for a, b in itertools.product(list1, list2):
  foo(a, b)

for任意の数のイテラブルを処理でき、その意味でネストされたループよりも一般的です。

于 2012-05-02T17:19:11.353 に答える