a, b, c = 1, 2, 3
【对比Cpp里:c = a >b? a:b】这个写法,只能常规的空行,缩进吗?
人生苦短,我用python,下面介绍几种if的方便的方法。
1.常规
if a>b:
c = a
else:
c = b
2.表达式
c = a if a>b else b
3.二维列表
c = [b,a][a>b]
········································································
还有for 循环的 用list解析的
[对(x)的操作 for x in 集合 if 条件]
[对(x,y)的操作 for x in 集合1 for y in 集合2 if 条件]
举一个简单的例子:
x=[1,2,3,4]
y=[5,6,7,8]
我想让着两个list中的偶数分别相加,应该结果是2+6,4+6,2+8,4+8
下面用一句话来写
- [a + b for a in x for b in y if a%2 == 0 and b%2 ==0]
之前的博客里用到的
- import os
- from os.path import join, getsize
- def getdirsize(dir):
- size = 0L
- for root, dirs, files in os.walk(dir):
- size += sum([getsize(join(root, name)) for name in files])
- return size
- [ x for x in one if x%2==0 ]