7

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

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

>>> [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

Error: User Rate Limit Exceededlambda:iError: User Rate Limit Exceeded

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

Error: User Rate Limit Exceeded

Error: User Rate Limit Exceeded

1

Error: User Rate Limit Exceeded

Error: User Rate Limit Exceeded

0

Error: User Rate Limit Exceeded

Error: User Rate Limit Exceeded(i for i in range(10))Error: User Rate Limit ExceedediError: User Rate Limit Exceeded

Error: User Rate Limit Exceededxrange(10)Error: User Rate Limit Exceeded

def f(x):
    return x

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

Error: User Rate Limit Exceededj()Error: User Rate Limit ExceededjError: User Rate Limit ExceededjError: User Rate Limit Exceeded

7

Error: User Rate Limit ExceededError: User Rate Limit ExceededError: User Rate Limit Exceeded

Error: User Rate Limit ExceedediError: User Rate Limit ExceedediError: User Rate Limit Exceeded

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

Error: User Rate Limit Exceeded

Error: User Rate Limit Exceeded

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

Error: User Rate Limit Exceeded

13

Error: User Rate Limit ExceededlambdaError: User Rate Limit ExceedediError: User Rate Limit ExceededlambdaError: User Rate Limit ExceedediError: User Rate Limit Exceeded

Error: User Rate Limit ExceedediError: User Rate Limit ExceededlambdaError: User Rate Limit Exceeded

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

Error: User Rate Limit Exceededlambda:

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]

Error: User Rate Limit ExceedediError: User Rate Limit Exceededcreate_lambda.

RelatedQuestions