Problem1:
Why is the output of the following two list comprehensions different, even though f
and the lambda
function are the same?
f = lambda x: x*x
[f(x) for x in range(10)]
and
[lambda x: x*x for x in range(10)]
Mind you, both type(f)
and type(lambda x: x*x)
return the same type.
-------------------------------------------------------------------------------------------------------------------------
The first one create a single lambda function and calls it ten times.
The second one doesn't call the function. It creates 10 different lambda functions. It puts all of those in a list. To make it equivalent to the first you need:
[(lambda x: x*x)(x) for x in range(10)]
Or better yet:
[x*x for x in range(10)]
Problem 2: how to use where???
fib = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
result = filter(lambda x: x % 2, fib)
print(result)
print(list(result))
result = filter(lambda x: x % 2 == 0, fib)
print(list(result))
print([i for i in fib if i % 2 == 0])
Problem 3: for and else together???
when the for condition fails, else will be executed once
'''
1
2
----------------------
'''
for i in range(1,4):
print(i)
if (i == 2):
break
else:
print('Finished! i = {0}'.format(i))
print('----------------------')
'''
1
2
3
Finished! i = 3
----------------------
'''
for i in range(1,4):
print(i)
else:
print('Finished! i = {0}'.format(i))
print('----------------------')
Problem 4: all and any
#any(x)判断x对象是否为空对象,如果都为空、0、false,则返回false,如果不都为空、0、false,则返回true
#all(x)如果all(x)参数x对象的所有元素不为0、''、False或者x为空对象,则返回True,否则返回False
all和any里面可以是list或者是tuple,也可以直接写list里的lambda表达式:
print(any(x*x == 9 for x in range(9))) #True
print(all(x*x == 9 for x in range(3,4))) #True