如何写出pythonic的代码,让代码显得高大上?
有很多应用场景需要用到python去过滤或者加工集合中的数据,自然会用到列表推导或者lambda表达式
#过滤数组中模2为0的数|采用列表推导
a = [x for x in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] if x % 2 == 1]
#过滤数组中模2为0的数|采用map/filter/lambda
s = list(filter(lambda n: n % 2 == 1, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))
print(s)
print(a)
#结果:
[1, 3, 5, 7, 9]
[1, 3, 5, 7, 9]