range()函数
range()语法:range(start, stop[, step])
# for循环
list_a = list()
for a in range(5):
list_a.append(a)
print(list_a)
[0, 1, 2, 3, 4]
# 列表推导式
list_b = [b for b in range(5)]
print(list_b)
[0, 1, 2, 3, 4]
# in后面跟其他可迭代对象,如字符串
list_c = [7 * c for c in "python"]
print(list_c)
# 带if条件语句的列表推导式
list_d = [d for d in range(6) if d % 2 != 0]
print(list_d)
# 多个for循环
list_e = [(e, f * f) for e in range(3) for f in range(5, 15, 5)]
print(list_e)
# 嵌套列表推导式,多个并列条件
list_g = [[x for x in range(g - 3, g)] for g in range(22) if g % 3 == 0 and g != 0]
print(list_g)
[‘ppppppp’, ‘yyyyyyy’, ‘ttttttt’, ‘hhhhhhh’, ‘ooooooo’, ‘nnnnnnn’]
[1, 3, 5]
[(0, 25), (0, 100), (1, 25), (1, 100), (2, 25), (2, 100)]
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11], [12, 13, 14], [15, 16, 17], [18, 19, 20]]
# 因为key是唯一的,所以最后value都是1
dict_a = {key: value for key in 'python' for value in range(2)}
print(dict_a)
# 可以根据键来构造值
dict_b = {key: key * key for key in range(6)}
print(dict_b)
# 遍历一个有键值关系的可迭代对象
list_phone = [('HUAWEI', '华为'), ('MI', '小米'), ('OPPO', 'OPPO'), ('VIVO', 'VIVO')]
dict_c = {key: value for key, value in list_phone}
print(dict_c)
{‘p’: 1, ‘y’: 1, ‘t’: 1, ‘h’: 1, ‘o’: 1, ‘n’: 1}
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
{‘HUAWEI’: ‘华为’, ‘MI’: ‘小米’, ‘OPPO’: ‘OPPO’, ‘VIVO’: ‘VIVO’}
# 遍历一个可迭代对象生成集合
set_a = {value for value in '有人云淡风轻,有人负重前行'}
print(set_a)
{‘负’, ‘有’, ‘人’, ‘轻’, ‘前’, ‘云’, ‘重’, ‘,’, ‘淡’, ‘风’, ‘行’}
集合是无序且不重复的,所以会自动去掉重复的元素,并且每次运行显示的顺序不一样.
集合推导式就是将列表推导式的[]换成{},字典推导式就是推导出两个值并构建成键值对的样子.
不管是字典推导式还是集合推导式,后面都可以像列表推导式一样接if条件语句,嵌套循环等,具体可以根据您自己的需求来使用.