标签:pycha 函数 charm items rgb start 变量 包括 ems
日常工作中,range() 应该非常熟悉了,它可以生成一个迭代对象,然后可以使用 list() 将它转成一个 list
# 判断是不是迭代对象 print(isinstance(range(0, 10), Iterable)) # 生成列表 lists = list(range(0, 10)) print(lists) # 输出结果 True [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
range(stop)
range(start, stop[, step])
返回一个迭代对象,它是一个整型序列,从 start 开始,然后到 stop(不包括)结束,当然也可以设置它的步进 step
for i in range(5): print(i) for i in range(10, 15): print(i) for i in range(5, 25, 5): print(i)
0
1
2
3
4
10
11
12
13
14
5
10
15
20
res = [] for i in range(11): res.append(i * i) print(res) # 输出结果 [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
但很明显繁琐了很多
针对上面的问题,列表生成式一句代码即可完成
res = [i * i for i in range(11)] print(res) # 输出结果 [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
# 筛选偶数 res = [i * i for i in range(11) if i % 2 == 0] print(res) # 输出结果 [0, 4, 16, 36, 64, 100]
res = [] for i in range(11): if i % 2 == 0: res.append(i * i)
res = [i + j for i in range(5) for j in range(6, 11)] print(res) # 输出结果 [6, 7, 8, 9, 10, 7, 8, 9, 10, 11, 8, 9, 10, 11, 12, 9, 10, 11, 12, 13, 10, 11, 12, 13, 14]
res = [] for i in range(5): for j in range(6, 11): res.append(i + j)
d = {‘x‘: ‘A‘, ‘y‘: ‘B‘, ‘z‘: ‘C‘} res = [(k, v) for k, v in d.items()] print(res) # 输出结果 [(‘x‘, ‘A‘), (‘y‘, ‘B‘), (‘z‘, ‘C‘)]
d = {‘x‘: ‘A‘, ‘y‘: ‘B‘, ‘z‘: ‘C‘} res = [] for k, v in d.items(): res.append((k, v))
L = [‘Hello‘, ‘World‘, ‘IBM‘, ‘Apple‘] res = [s.lower() for s in L] print(res) # 输出结果 [‘hello‘, ‘world‘, ‘ibm‘, ‘apple‘]
res = [i * i for i in range(11) if i % 2 == 0 else 0] print(res) # 报错信息 res = [i * i for i in range(11) if i % 2 == 0 else 0] ^ SyntaxError: invalid syntax
res = [i if i % 2 == 0 for i in range(11)] print(res) # 报错信息 res = [i if i % 2 == 0 for i in range(11)] ^ SyntaxError: invalid syntax
for 前面是一个表达式,它需要有个表达式计算结果,只有 if 是不完整的,需要有 else
res = [i if i % 2 == 0 else "奇数" for i in range(11)] print(res) # 输出结果 [0, ‘奇数‘, 2, ‘奇数‘, 4, ‘奇数‘, 6, ‘奇数‘, 8, ‘奇数‘, 10]
将 if ... else 放在前面写
标签:pycha 函数 charm items rgb start 变量 包括 ems
原文地址:https://www.cnblogs.com/poloyy/p/14659472.html