Python if 和 for 的多种写法

a, b, c = 123

【对比Cpp里:c = a >b? a:b】这个写法,Python只能常规的空行,缩进吗?

人生苦短,我用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

下面用一句话来写

 

[python] view plain copy 在CODE上查看代码片派生到我的代码片
  1. [a + b for a in x for b in y if a%2 == and b%2 ==0]  

之前的博客里用到的

 

[python] view plain copy 在CODE上查看代码片派生到我的代码片
  1. import os  
  2. from os.path import join, getsize  
  3.   
  4. def getdirsize(dir):  
  5.    size = 0L  
  6.    for root, dirs, files in os.walk(dir):  
  7.       size += sum([getsize(join(root, name)) for name in files])  
  8.    return size  


 

[python] view plain copy 在CODE上查看代码片派生到我的代码片
  1. [ x for x in one if x%2==0 ]  

 
 
原文地址:https://www.cnblogs.com/zknublx/p/6206670.html