1

こんにちは、このコードは python 2.7 では動作しますが、python 3 では動作しません

import itertools
def product(a,b):
    return map(list, itertools.product(a, repeat=b)
print(sorted(product({0,1}, 3)))

それは出力します

  [[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 0, 1], [1, 1, 0], [1, 1, 1]]

Python 2.7では、しかしPython 3では、0x028DB2F0でマップオブジェクトを提供します。これをPython 3で機能するように変更する方法を知っている人はいますか?出力はPython 2.7と同じままです

4

2 に答える 2

2

このようにリストでラップするだけです:

import itertools

def product(a,b):
    return list(map(list, itertools.product(a, repeat=b))

print(sorted(product({0,1}, 3)))

Python 3.x でリストを返すための map() の取得

Python 3マップの2つの言葉で

関数を iterable のすべてのアイテムに適用し、結果を生成するイテレータを返します。

python 2.7では

関数を iterable のすべてのアイテムに適用し、結果のリストを返します。

于 2013-03-27T01:34:56.013 に答える
1

Python 3 では、map()ビルトインはリストではなくイテレータを返し、Python 2itertools.imap()関数のように動作します。

リストが必要な場合は、単純にそのイテレータを に渡すことができますlist()。例えば:

>>> x = map(lambda x: x + 1, [1, 2, 3])
>>> x
<map object at 0x7f8571319b90>
>>> list(x)
[2, 3, 4]
于 2013-03-27T01:35:41.627 に答える