python常用技巧
2018-05-21 11:48
148 查看
1,列表推导已知一个列表,刷选出偶数列表方法:
numbers = [1,2,3,4,5,6] even = [] for number in numbers: if number%2 == 0: even.append(number)用下面的代替
numbers = [1,2,3,4,5,6] even = [number for number in numbers if number%2 == 0]2,字典推导
teams = ["Packers", "49ers", "Ravens", "Patriots"]print {key: value for value, key in enumerate(teams)}>>> {'49ers': 1, 'Ravens': 2, 'Patriots': 3, 'Packers': 0}
3,枚举 - enumerate
之前我们这样操作:iterable = 'asdfghjk' i = 0 for item in iterable: print(i, " ", item) i += 1
现在我们这样操作:
iterable='asdfghjk' for i, item in enumerate(iterable): print(i, " ", item)
enumerate函数还可以接收第二个参数。就像下面这样:
list(enumerate('abc')) # [(0, 'a'), (1, 'b'), (2, 'c')] list(enumerate('abc', 1)) # [(1, 'a'), (2, 'b'), (3, 'c')]
4,字典/集合 生成
my_dict = {i: i * i for i in range(10)} # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81} my_set = {i * 15 for i in range(10)} # {0, 135, 105, 75, 45, 15, 120, 90, 60, 30}列表解析
5,交换变量
x = 6y = 5 x, y = y, x print x>>> 5print y>>> 6
6,两个列表同时迭代
nfc = ["Packers", "49ers"]afc = ["Ravens", "Patriots"]for teama, teamb in zip(nfc, afc): print teama + " vs. " + teamb>>> Packers vs. Ravens>>> 49ers vs. Patriots
7,将列表转换成字符串
teams = ["Packers", "49ers", "Ravens", "Patriots"]print ", ".join(teams)>>> 'Packers, 49ers, Ravens, Patriots'
8,从字典中获取元素
不要用下列的方式
data = {'user': 1, 'name': 'Max', 'three': 4} try: is_admin = data['admin'] except KeyError: is_admin = False替换为
data = {'user': 1, 'name': 'Max', 'three': 4} is_admin = data.get('admin', False)
9,60个字符解决FizzBuzz
#写一个程序,打印数字1到100,3的倍数打印“Fizz”来替换这个数,5的倍数打印“Buzz”,对于既是3的倍数又是5的倍数的数字打印“FizzBuzz”。
for x in range(1, 101):print("Fizz"[x%3*4:]+"Buzz"[x%5*4:] or x)
10,集合 用到Counter库
from collections import Counterprint Counter("hello")>>> Counter({'l': 2, 'h': 1, 'e': 1, 'o': 1})
11,迭代工具 和collections库一样,还有一个库叫itertools
from itertools import combinationsteams = ["Packers", "49ers", "Ravens", "Patriots"]for game in combinations(teams, 2): print game>>> ('Packers', '49ers')>>> ('Packers', 'Ravens')>>> ('Packers', 'Patriots')>>> ('49ers', 'Ravens')>>> ('49ers', 'Patriots')>>> ('Ravens', 'Patriots')
相关文章推荐
- 常用的 Python 爬虫技巧总结
- Python 中一些常用技巧
- python使用Image处理图片常用技巧分析
- Python爬虫学习之常用技巧详解
- Python爬虫常用小技巧之设置代理IP
- Python SQLAlchemy基本操作和常用技巧
- 一些常用的python爬虫技巧总结
- python爬虫:一些常用的爬虫技巧
- Python常用技巧(持续更新)
- python 的一些常用技巧
- Python常用网页字符串处理技巧
- Python Django REST framework 常用技巧
- python学习笔记-常用技巧整理
- Python SQLAlchemy基本操作和常用技巧(包含大量实例,非常好)
- Python爬虫:一些常用的爬虫技巧总结
- 一些常用的python爬虫技巧总结【文末彩蛋福利】
- 常用几个Python高效编程技巧
- Python SQLAlchemy基本操作和常用技巧(包含大量实例,非常好)
- Python常用函数与技巧总结(二)
- [Python]常用技巧之CSV处理