Python优雅编程技巧
来源:互联网 发布:linux 启动ntp客户端 编辑:程序博客网 时间:2024/05/17 09:39
Python开发的10个小技巧
标签(空格分隔): Python
1. 列表推导式
需求:把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]
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 = 5b = 6#交换a和btmp = aa = bb = tmp
优雅的方式:
a = 5b = 6#交换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]]
所有元素都被改变了,而我们只想改变第一个列表。
正确的方法:
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. 构造字符串不用+
,使用.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)
6. 返回元祖(tuples
)
Python允许你在一个函数中返回多个元素,这让生活更简单。
普通的方式:
def binary(): return 0, 1result = binary() zero = result[0] one = result[1]
优雅的方式:
def binary(): return 0, 1zero, one = binary()
7. 访问字典(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] = 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)))
当然你也可以用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
被调用时都会对列表遍历。
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. 在列表中切片/步进
你可以指定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)# 或者用 rangesbag = 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
- Python优雅编程技巧
- python优雅编程技巧
- Python优雅技巧
- 【译】Python的优雅技巧
- 译|一些Python优雅技巧
- Python高效编程技巧
- Python高效编程技巧
- Python高效编程技巧
- Python高效编程技巧
- Python高效编程技巧
- Python高效编程技巧
- Python高效编程技巧
- Python高级编程技巧
- Python高级编程技巧
- Python高级编程技巧
- Python高级编程技巧
- Python高级编程技巧
- Python高级编程技巧
- 数据分类K—means 算法的python代码实现
- Open Investor简介
- KMP算法(c++)实现
- struts2框架之struts框架介绍
- http和socket之长连接和短连接区别
- Python优雅编程技巧
- 30多个HTML5经典动画应用展示
- Process the Tasks(ZOJ3331)
- 项目4-静态成员应用
- View事件面试总结21问21答。
- 游戏中的角色类1
- 第四周 项目5(2)
- 重载函数调用运算符()
- AOP笔记