[Python] Some Tips
Table of Contents
原帖: Python开发的10个小贴士
Tips 1: List Comprehension
[Python] Comprehensions Concepts
Tips 2: Directly Get Value of List object
Bad
bag = [1, 2, 3, 4, 5]
for i in range(len(bag)):
print(bag[i])
Good
bag = [1, 2, 3, 4, 5]
for i in bag:
print(i)
Get the index of list itme if you need
bag = [1, 2, 3, 4, 5]
for index, element in enumerate(bag):
print(index, element)
Tips 3: Exchange the value of variables
Bad
a = 5
b = 10
tmp = a
a = b
b = tmp
Good
a = 5
b = 10
a, b = b, a
Tips 4: Initialize List
General
bag = []
for _ in range(10):
bag.append(0)
Good
bag = [0]*10
Trap: Shallow copy
bag = [[0]] * 5
The result is NOT what we want.
bag[0][0] = 1
The result of bag will be [[1],[1],[1],[1],[1]]
.
bag = [[0] for _ in range(5)]
bag[0][0] = 1
The result of bag will be [[1],[0],[0],[0],[0]]
Tips 5: String Access
Bad
name = "Raymond"
age = 22
born_in = "Oakland, CA"
string = "Hello my name is " + name + "and I'm " + str(age) + " years old. I was born in " + born_in + "."
print(string)
Good
name = "Raymond"
age = 22
born_in = "Oakland, CA"
string = "Hello my name is {0} and I'm {1} years old. I was born in {2}.".format(name, age, born_in)
print(string)
Tips 6: Return tuples
Bad
def binary():
return 0, 1
result = binary()
zero = result[0]
one = zero[1]
Good
zero, one = binary()
or
zero, _ = binary()
Tips 7: Get the value of Dict by dict.get() with default value.
Not Good
一般對於不存在的 dictionary key/value, 為了避免 KeyError
, 會用如下的寫法完成 error handling.
countr = {}
bag = [2, 3, 1, 2, 5, 6, 7, 9, 2, 7]
for i in bag:
if i in countr:
countr[i] += 1
else:
countr[i] = 1
for i in range(10):
if i in countr:
print("Count of {}: {}".format(i, countr[i]))
else:
print("Count of {}: {}".format(i, 0))
Good
可以使用 dict.get(key, defaultValue)
來完成避免 KeyError
的 error handling.
countr = {}
bag = [2, 3, 1, 2, 5, 6, 7, 9, 2, 7]
for i in bag:
countr[i] = countr.get(i, 0) + 1
for i in range(10):
print("Count of {}: {}".format(i, countr.get(i, 0)))
Tips 8: List Slice
List [ Start: Stop: Step ]
取前 5 個元素
bag = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
for elem in bag[:5]:
print(elem)
取後 5 個元素
bag = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
for elem in bag[-5:]:
print(elem)
每隔 2 個取一個元素
bag = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
for elem in bag[::2]:
print(elem)
從後頭數過來取元素
bag = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
for elem in bag[::-1]:
print(elem)