Abstract:
Skills how to simplify loop and if statements
1. If statement
The common pattern
of If statement:
>>> a
10
>>> if a==10:
... print 'a=', a
... else:
... print "hello"
...
a= 10
Here is a simple
pattern:
>>> print 'a=', a if a==10 else "hello"
#print
a= 10
>>> print 'a=', a if a==10 else "hello"
a= 10
>>> b=a if a==10 else 100 # assignment
>>> print b
10
>>> b=a if a<10 else 100
>>> print b
100
2. For statement
The common pattern:
>>> a=range(10)
>>> for i in a:
... if i%2==0:
... print i
0
2
4
6
8
This is a simpler
pattern:
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> even=[i for i in a if i%2 == 0]
>>> print even
[0, 2, 4, 6, 8]
writing date:
20150522
No comments:
Post a Comment