python|python 简单推导式
1. []列表推导
print([x * x for x in range(10)])# 添加if
print([x * x for x in range(10) if x % 3 == 0])# 更多的for
print([(x, y) for x in range(3) for y in range(4)])# 例子
girls = ['alice', 'bernice', 'clarice']
boys = ['chris', 'arnold', 'bob']
letterGirls = {}
for girl in girls:
letterGirls.setdefault(girl[0], []).append(girl)
print([boy + '+' + girl for boy in boys for girl in letterGirls[boy[0]]])
========================1=========================
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
[0, 9, 36, 81]
[(0, 0), (0, 1), (0, 2), (0, 3), (1, 0), (1, 1), (1, 2), (1, 3), (2, 0), (2, 1), (2, 2), (2, 3)]
['chris+clarice', 'arnold+alice', 'bob+bernice']
2. {}字典推导
squares = { i: '{} squared is {}'.format(i, i**2) for i in range(10)}
print(squares[8])
========================2=========================
8 squared is 64
3. ()创建生成器
generator = (x * x for x in range(10))
print(generator)
========================3=========================
at 0x00000292DF34AA98>
推荐阅读
- python学习之|python学习之 实现QQ自动发送消息
- 科学养胃,别被忽悠,其实真的很简单
- 逻辑回归的理解与python示例
- opencv|opencv C++模板匹配的简单实现
- python自定义封装带颜色的logging模块
- 【Leetcode/Python】001-Two|【Leetcode/Python】001-Two Sum
- Python基础|Python基础 - 练习1
- 松软可口易消化,无需烤箱超简单,新手麻麻也能轻松成功~
- Python爬虫|Python爬虫 --- 1.4 正则表达式(re库)
- Python(pathlib模块)