标签:module lex value 变量 filter 表达式 mod pythonic iso
tmp = a a = b b = tmp
a,b = b,a
my_list = [] for i in range(10): my_list.append(i*2)
my_list = [i*2 for i in range(10)]
虽然列表推导式由于其简洁性及表达性,被广受推崇。
但是有许多可以写成单行的表达式,并不是好的做法。
print ‘one‘; print ‘two‘ if x == 1: print ‘one‘ if <complex comparison> and <other complex comparison>: # do something
for i in range(len(my_list)): print(i, "-->", my_list[i])
for i,item in enumerate(my_list): print(i, "-->",item)
a, *rest = [1, 2, 3] # a = 1, rest = [2, 3] a, *middle, c = [1, 2, 3, 4] # a = 1, middle = [2, 3], c = 4
letters = [‘s‘, ‘p‘, ‘a‘, ‘m‘] s="" for let in letters: s += let
letters = [‘s‘, ‘p‘, ‘a‘, ‘m‘] word = ‘‘.join(letters)
if attr == True: print ‘True!‘ if attr == None: print ‘attr is None!‘
if attr: print ‘attr is truthy!‘ if not attr: print ‘attr is falsey!‘ if attr is None: print ‘attr is None!‘
d = {‘hello‘: ‘world‘} if d.has_key(‘hello‘): print d[‘hello‘] # prints ‘world‘ else: print ‘default_value‘
d = {‘hello‘: ‘world‘} print d.get(‘hello‘, ‘default_value‘) # prints ‘world‘ print d.get(‘thingy‘, ‘default_value‘) # prints ‘default_value‘ # Or: if ‘hello‘ in d: print d[‘hello‘]
a = [3, 4, 5] b = [] for i in a: if i > 4: b.append(i)
a = [3, 4, 5] b = [i for i in a if i > 4] # Or: b = filter(lambda x: x > 4, a)
a = [3, 4, 5] for i in range(len(a)): a[i] += 3
a = [3, 4, 5] a = [i + 3 for i in a] # Or: a = map(lambda i: i + 3, a)
f = open(‘file.txt‘) a = f.read() print a f.close()
with open(‘file.txt‘) as f: for line in f: print line
my_very_big_string = """For a long time I used to go to bed early. Sometimes, when I had put out my candle, my eyes would close so quickly that I had not even time to say “I‘m going to sleep.”""" from some.deep.module.inside.a.module import a_nice_function, another_nice_function, yet_another_nice_function
my_very_big_string = ( "For a long time I used to go to bed early. Sometimes, " "when I had put out my candle, my eyes would close so quickly " "that I had not even time to say “I‘m going to sleep.”" ) from some.deep.module.inside.a.module import ( a_nice_function, another_nice_function, yet_another_nice_function)
def make_complex(*args): x, y = args return dict(**locals())
def make_complex(x, y): return {‘x‘: x, ‘y‘: y}
filename = ‘foobar.txt‘ basename, _, ext = filename.rpartition(‘.‘)
if age > 18 and age < 60: print("young man")
if 18 < age < 60: print("young man")
理解了链式比较操作,那么你应该知道为什么下面这行代码输出的结果是 False
>>> False == False == True
False
if a > 2: b = 2 else: b = 1 #b = 2
a = 3 b = 2 if a > 2 else 1 #b = 2
标签:module lex value 变量 filter 表达式 mod pythonic iso
原文地址:https://www.cnblogs.com/tracydzf/p/13976215.html