a = 10 b = 20 a, b = b, a print(b, a) print(a, b)
輸出:python
10 20 20 10
n = 10 print(6 < n < 20) print(11 < n < 20)
輸出:函數
True False
# [表達式爲真的返回值] if [表達式] else [表達式爲假的返回值] a = 10 b = 1 if a == 0 else 0 print(b)
輸出:code
0
a = [1,4,5,6,2,8,3,7,9] b = [i for i in a if i > 5] print(b) c = [(0,1), (2,3), (4,6)] d = [r[1] for r in c] print(d)
輸出:索引
[6, 8, 7, 9] [1, 3, 6]
a = [1,2,3,4,5,6] # (1,2,3,4,5,6) b = a[2:] c = a[1:2] # 半閉半開 print(b) print(c)
輸出:ip
[3, 4, 5, 6] [2]
a = [1,2,3,3,2,4,5] print(a.count(2))
輸出:字符串
2
a = [1,2,3,3,2,4,5] # 方法1 from collections import Counter b = Counter(a) print(b) # 方法2 c = { i: a.count(i) for i in set(a) } print(c)
輸出:get
Counter({2: 2, 3: 2, 1: 1, 4: 1, 5: 1}) {1: 1, 2: 2, 3: 2, 4: 1, 5: 1}
a = [1,2,3,3,2,4,5] b = list(set(a)) print(a, b)
輸出:it
[1, 2, 3, 3, 2, 4, 5] [1, 2, 3, 4, 5]
a = [['name','Robin'], ['age',30]] b = { r[0]: r[1] for r in a } print(b)
輸出:io
{'name': 'Robin', 'age': 30}
a = [['name','Robin'], ['age',30]] b = dict(a) print(b)
輸出:class
{'name': 'Robin', 'age': 30}
a = {'name':'Robin', 'age':30} print(list(a.items()))
輸出:
[('name', 'Robin'), ('age', 30)]
a = [1,2,3,4] b = ['a','b','c','d'] c = zip(a, b) print(list(c))
輸出:
[(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd')]
a = 'a' b = a * 10 print(b)
輸出:
aaaaaaaaaa
a = ['Hello', 'World', '!'] b = '~'.join(a) print(b)
輸出:
Hello~World~!
a = 'Hello World !' print('World' in a) print('abc' in a)
輸出:
True False
a = 1 if a == 1 or a == 2 or a == 3 or a == 8: pass # 不推薦作法 if a in [1,2,3,8,9]: pass # 推薦作法
輸出:
# 醜代碼 a = ['A', 'B', 'C'] n = 0 for i in a: print(n, i) n += 1 for i in range(len(a)): print(i, a[i]) # 推薦代碼 for n, i in enumerate(a): print(n, i)
輸出:
0 A 1 B 2 C 0 A 1 B 2 C 0 A 1 B 2 C
def test(a, b, *args, **kwargs): print(a, b, args, kwargs) test(1,2) test(1,2,3,4,t=5) n = [4,5] m = {'x':6, 'y':7} test(1,2, *n, **m) # 結構傳遞,等同test(1,2,3,4,x=6,y=7)
輸出:
1 2 () {} 1 2 (3, 4) {'t': 5} 1 2 (4, 5) {'x': 6, 'y': 7}
a = [{'name':'A', 'id':1}, {'name':'B', 'id':2}] b = map(lambda d:d['id'], a) print(list(b)) # 列表推導實現 c = [d['id'] for d in a] print(c)
輸出:
[1, 2] [1, 2]
a = [1,4,5,6,2,8,3,7,9] b = filter(lambda i: i > 5, a) print(list(b)) # 列表推導實現 c = [i for i in a if i > 5] print(c)
輸出:
[6, 8, 7, 9] [6, 8, 7, 9]
a = [1,2,3,3,2,4,5] print(max(a)) print(min(a)) print(sum(a))
輸出:
5 1 20
# 醜代碼 a = 1 if a == 1: b = 'A' elif a == 2: b = 'B' else: b = 'C' print(b) # 簡化代碼 d = {1:'A', 2:'B'} b = d.get(a, 'C') print(b)
輸出:
A A