次のコードが出力されない理由を教えて[1,2,3,1,2,3]
ください。代わりに、例外をスローします。それを機能させる方法を教えてください。
x = [1,2,3]
print apply(lambda x: x * 2, (x))
次のことを試してみると、うまくいきます:
test1 = lambda x: x * 2
print test1(x)
これは機能します
x = [1,2,3]
print apply(lambda x: x * 2, [x])
ただし、apply
Python 2.3 以降非推奨になっていることに注意してください。
http://docs.python.org/2/library/functions.html#apply
Deprecated since version 2.3: Use function(*args, **keywords) instead of apply(function, args, keywords). (see Unpacking Argument Lists)
apply
2 番目の引数 (タプル/リストである必要があります) を取り、このタプルの各要素を位置引数apply
として、最初の引数として渡したオブジェクトに渡します。
つまりx = [1,2,3]
、あなたが呼び出す場合
apply(lambda x: x * 2, (x))
apply
1
は引数、2
、および を指定してラムダ関数を呼び出しますが、ラムダ関数は引数3
を 1 つしかとらないため失敗します。
それを機能x
させるには、タプルまたはリストにする必要があります。
print apply(lambda x: x * 2, [x])
また
# note the extra ','. (x,) is a tuple; (x) is not.
# this is probably the source of your confusion.
print apply(lambda x: x * 2, (x,))
たぶん私はあなたの質問を理解していませんが、必要なのがリストを「乗算」することだけである場合は、単にそれを乗算します。
xx = [1,2,3]
print(xx * 2)