# Python 3 那些非常规的技巧

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 和 b

tmp = a

a = b

b = tmp

a = 5

b = 10

# 交换a 和 b

a, 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. 返回

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

def binary:

return 0, 1

result = binary

zero = result[0]

one = result[1]

def binary:

return 0, 1

zero, one = binary

zero, _ = binary

7. 访问

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

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)

# 或者用 ranges

bag = list(range(0,10,2))

print(bag)

10. tab键还是空格键

1683 篇文章143 人订阅

0 条评论

## 相关文章

32840

12730

### Python程序结构

4种流程控制语句结构： if if -- else if -- elif --else if多条件

38120

400100

41180

9920

24840

### Java Map集合面试题汇总

1、 你都知道哪些常用的Map集合2、Collection集合接口和Map接口有什么关系？ 3、HashMap是线程安全的吗？线程安全的Map都有哪些？性能最好...

42860

### 《笨办法学Python》 第18课手记

《笨办法学Python》 第18课手记 本节课将创建函数，跟C语言里面的的定义函数差不多。 作者在每个函数开头都加了解释该函数功能的英文注释。为了方便理解，我将...

21380

9530