# Python开发的十个Tips，你知道几个？

【题外话】最近磐创AI寻找“深大锦鲤”活动是2018年10月15日晚21：00准时开奖哦~听说除了送520现金之外，在文末留言点赞第一名还可以获得200元当当购书券欸，快去留言叫小伙伴帮你点赞吧~活动链接：寻找深大锦鲤，会不会是你？(抽520现金大礼包)。欢迎大家点击上方蓝字关注我们的公众号：磐创AI。

## 1. 列表推导式

`bag = [1, 2, 3, 4, 5]  for i in range(len(bag)):      bag[i] = bag[i] * 2`

`bag = [elem * 2 for elem in bag]`

## 2. 遍历列表

`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)`

## 3. 元素互换

`a = 5 b = 10# 交换 a 和 btmp = a  a = b  b = tmp`

`a = 5  b = 10  # 交换a 和 ba, b = b, a`

## 4. 初始化列表

`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]]`

Oops！所有的列表都改变了，而我们只是想要改变第一个列表。

`bag_of_bags = [[0] for _ in range(5)]  # [[0], [0], [0], [0], [0]]bag_of_bags[0][0] = 1  # [[1], [0], [0], [0], [0]]`

“过早优化是万恶之源”

## 5. 构造字符串

`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)`

## 6. 返回`tuples`（元组）

Python允许你在一个函数中返回多个元素，这让生活更简单。但是在解包元组的时候出出线这样的常见错误：

`def binary():      return 0, 1result = binary()  zero = result[0]  one = result[1]`

`def binary():      return 0, 1zero, one = binary()`

`zero, _ = binary()`

## 7. 访问`Dicts`（字典）

`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] = 1for 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) + 1for i in range(10):      print("Count of {}: {}".format(i, countr.get(i, 0)))`

`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)))`

`countr = {num: bag.count(num) for num in bag}`

## 8 使用库

`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]))`

• 代码是正确而且经过测试的。

• 它们的算法可能会是最优的，这样就跑的更快。

• 抽象化：它们指向明确而且文档友好，你可以专注于那些还没有被实现的。

• 最后，它都已经在那儿了，你不用再造轮子了。

## 9. 在列表中切片/步进

`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 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)# 或者用 rangesbag = list(range(0,10,2))  print(bag)`

点击下方 |  | 了解更多