Вопрос по python – Лямбды внутри списка

7

Я хотел получить список лямбд, которые служат своего рода кэшем для некоторых тяжелых вычислений, и заметил это:

>>> [j() for j in [lambda:i for i in range(10)]]
[9, 9, 9, 9, 9, 9, 9, 9, 9, 9]

Хотя

>>> list([lambda:i for i in range(10)])
[<function <lambda> at 0xb6f9d1ec>, <function <lambda> at 0xb6f9d22c>, <function <lambda> at 0xb6f9d26c>, <function <lambda> at 0xb6f9d2ac>, <function <lambda> at 0xb6f9d2ec>, <function <lambda> at 0xb6f9d32c>, <function <lambda> at 0xb6f9d36c>, <function <lambda> at 0xb6f9d3ac>, <function <lambda> at 0xb6f9d3ec>, <function <lambda> at 0xb6f9d42c>]

Error: User Rate Limit Exceeded

Error: User Rate Limit Exceeded

>>> funcs = []
... for i in range(10):
...     funcs.append(lambda:i)
... [j() for j in funcs]
[9, 9, 9, 9, 9, 9, 9, 9, 9, 9]

Ваш Ответ

5   ответов
0

lambda:i

>>> i=5
>>> x=lambda:i
>>> x()
5
>>> i=6
>>> x()
6

0

(i for i in range(10))i

xrange(10)

def f(x):
    return x

lst = [f(x) for x in xrange(10)]
print(lst == range(10))  # prints True

j()jj

7

ii

>>> y = 3
>>> f = lambda: y
>>> f()
3
>>> y = 4
>>> f()
4

>>> f = lambda y=y:y
>>> f()
4
>>> y = 6
>>> f()
4

Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
1

13

lambdailambdai

ilambda

>>> [j() for j in [lambda i=i:i for i in range(10)]]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

lambda:

def create_lambda(i):
    return lambda:i
>>> [j() for j in [create_lambda(i) for i in range(10)]]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

icreate_lambda.

Error: User Rate Limit ExceedediError: User Rate Limit Exceeded[lambda k=i:k for i in range(10)]Error: User Rate Limit Exceeded
Error: User Rate Limit ExceededlambdaError: User Rate Limit Exceeded*argsError: User Rate Limit Exceeded
Error: User Rate Limit ExceedediError: User Rate Limit Exceeded
Error: User Rate Limit Exceeded ubershmekel
Error: User Rate Limit ExceededkError: User Rate Limit Exceeded

Похожие вопросы