标签(空格分隔): Python
需求:把list
所有成员元素加倍。
普通的方式:
bag = [1,2,3,4,5]
for i in range(len(bag)):
bag[i] = bag[i] * 2
优雅的方式:
bag = [1,2,3,4,5]
bag = [elem * 2 for elem in bag]
普通的方式:
bag = [1,2,3,4,5]
for i in range(len(bag)):
print(bag[i])
优雅的方式:
bag = [1,2,3,4,5]
for i in bag:
print(i)
如果需要显示列表的索引,则可用以下方式:
bag = [1,2,3,4,5]
for index, element in enumerate(bag):
print(index, element)
普通的方式:
a = 5
b = 6
#交换a和b
tmp = a
a = b
b = tmp
优雅的方式:
a = 5
b = 6
#交换a和b
a, b = b, a
普通的方式:
bag = []
for _ in range(10):
bag.append(0)
优雅的方式:
bag = [0] * 10
注意:如果列表包含的列表,这样就产生了浅拷贝。
举个栗子:
bag_of_bags = [[0]] * 5 #[[0], [0], [0], [0], [0]]
bag_of_bags[0][0] = 1 #[[1], [1], [1], [1], [1]]
所有元素都被改变了,而我们只想改变第一个列表。
正确的方法:
bag_of_bags = [[0] for _ in range(5)] #[[0], [0], [0], [0], [0]]
bag_of_bags[0][0] = 1 #[[1], [0], [0], [0], [0]]
+
,使用.format
普通的方式:
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)
优雅的方式:
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)
tuples
)Python允许你在一个函数中返回多个元素,这让生活更简单。
普通的方式:
def binary():
return 0, 1
result = binary()
zero = result[0]
one = result[1]
优雅的方式:
def binary():
return 0, 1
zero, one = binary()
dicts
)你也会经常给dicts
中写入key,pair(键,值)
。
如果你试图访问一个不存在的于dict
的key
,可能会为了避免KeyError
错误,你会倾向于这样做:
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))
优雅的方式:
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)))
当然你也可以用setdefault来代替。
还有一个更简单却多费点开销的办法:
bag = [2, 3, 1, 2, 5, 6, 7, 9, 2, 7]
countr = dict([(num, bag.count(num)) for num in bag])
for i in range(10):
print("Count of {}: {}".format(i, countr.get(i, 0)))
你也可以用dict推导式
:
countr = {num: bag.count(num) for num in bag}
这两种方法开销大,因为它们在每次count
被调用时都会对列表遍历。
现有的库,直接导入使用好了。
举个例子,查找下一个数字在列表中出现的次数:
from collections import Counter
bag = [2, 3, 1, 2, 5, 6, 7, 9, 2, 7]
countr = Counter(bag)
for i in range(10):
print("Count of {}: {}".format(i, countr[i]))
你可以指定start
的点和stop
点,就像这样list[start:stop:step]
。我们取出列表中的前5个元素:
bag = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
for elem in bag[:5]:
print(elem)
这就是切片,我们指定stop点是5,再停止前就会从列表中取出5个元素。
要是最后5个元素怎么做?
bag = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
for elem in bag[-5:]:
print(elem)
如果想对列表中元素间隔操作,你可以这样做:
bag = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
for index, elem in enumerate(bag):
if index % 2 == 0:
print(elem)
更优雅的方式:
bag = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
for elem in bag[::2]:
print(elem)
# 或者用 ranges
bag = list(range(0,10,2))
print(bag)
这就是列表中的步进。list[::2]
意思是遍历列表同时两步取出一个元素。
你可以用list[::-1]
很酷的翻转列表。
译文链接:http://www.codeceo.com/article/python-10-tips.html
英文原文:The Python Way: 10
其他文档:
The Python Way Part Two: 10 More Tips
Python List Comprehensions: Explained Visually