g = lambda x:[lambda x:x*1, lambda x:x*x, lambda x:x*x*x, lambda x:42][x%4](x)
[g(x) for x in xrange(12)]
这个序列的下一个值是什么?
你试过了吗?
>>> g = lambda x:[lambda x:x*1, lambda x:x*x, lambda x:x*x*x, lambda x:42][x%4](x)
>>> [g(x) for x in xrange(12)]
[0, 1, 8, 42, 4, 25, 216, 42, 8, 81, 1000, 42]
以下是每个值的计算方式:
[
0, # x is 0, x%4 is 0, so g(x) becomes (lambda x:x*1)(0) or 0*1
1, # x is 1, x%4 is 1, so g(x) becomes (lambda x:x*x)(1) or 1*1
8, # x is 2, x%4 is 2, so g(x) becomes (lambda x:x*x*x)(2) or 2*2*2
42, # x is 3, x%4 is 3, so g(x) becomes (lambda x:42)(3) or 42
4, # x is 4, x%4 is 0, so g(x) becomes (lambda x:x*1)(4) or 4*1
25, # x is 5, x%4 is 1, so g(x) becomes (lambda x:x*x)(5) or 5*5
216, # x is 6, x%4 is 2, so g(x) becomes (lambda x:x*x*x)(6) or 6*6*6
42, # x is 7, x%4 is 3, so g(x) becomes (lambda x:42)(7) or 42
8, # x is 8, x%4 is 0, so g(x) becomes (lambda x:x*1)(8) or 8*1
81, # x is 9, x%4 is 1, so g(x) becomes (lambda x:x*x)(9) or 9*9
1000, # x is 10, x%4 is 2, so g(x) becomes (lambda x:x*x*x)(10) or 10*10*10
42 # x is 11, x%4 is 3, so g(x) becomes (lambda x:42)(11) or 42
]
基本上g(x)
以x
作为参数调用列表中的一个函数,当在列表推导中调用xrange
它时,它将循环遍历函数,每四个调用都是同一个函数。
我知道这只是一个有助于理解 Python 的练习,但您应该注意这是非常低效的代码,因为每次调用g()
. 如果您确实需要这种行为,最好只创建一个def
包含多个if
语句的函数(这也会使代码更具可读性)。
我会这样做以更好地了解正在发生的事情(如果您需要进一步解释,请发表评论)
In [44]: g = lambda x:[lambda x:x*1, lambda x:x*x, lambda x:x*x*x, lambda x:42][x%4](x)
In [45]: {x:g(x) for x in xrange(12)}
Out[45]:
{0: 0,
1: 1,
2: 8,
3: 42,
4: 4,
5: 25,
6: 216,
7: 42,
8: 8,
9: 81,
10: 1000,
11: 42}