Python Lambda表达式 for else all any

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

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值