Python range():表示某个范围内的数值
range函数作用
- Python 中的range是表示整数区间的对象,通常用for循环访问。
- range函数t转的对象可以转换为列表
- for i in range(5)是一个循环,它遍历从 0 到 4(包括 0 和 4)的数字。
- range函数参数 、start, stop, step左闭右开[start,end),step数字表示步长
- 在 Python 中,range可以使用负步长值向后移动,也可以使用 .reversed()
使用range函数
>>> list(range(5))
[0, 1, 2, 3, 4]
>>> list(range(1, 7))
[1, 2, 3, 4, 5, 6]
>>> list(range(1, 20, 2))
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
生成0, 1, 2, 3, 4这5个数字
range函数返回的对象
>>> range(5)
range(0, 5)
>>> list(range(1, 7))
[1, 2, 3, 4, 5, 6]
range(start,end,step)
>>> range(1, 20, 2)
range(1, 20, 2)
>>> list(range(1, 20, 2))
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
- range(1, 20, 2)其中2表示每次数字增2
使用负数生成range
>>> range(-10, 0)
range(-10, 0)
>>> list(range(-10, 0))
[-10, -9, -8, -7, -6, -5, -4, -3, -2, -1]
>>> range(-7, -3)
range(-7, -3)
>>> list(range(-7, -3))
[-7, -6, -5, -4]
使用空范围
>>> range(1, 1)
range(1, 1)
>>> list(range(1, 1))
[]
>>> range(0)
range(0, 0)
>>> list(range(0))
[]
使用负数的步长 range(5, -1, -1)
>>> range(5, -1, -1)
range(5, -1, -1)
>>> list(range(5, -1, -1))
[5, 4, 3, 2, 1, 0]
for循环的使用
遍历字符串
>>> word = "Loop"
>>> for index in range(len(word)):
... print(index, word[index])
...
0 L
1 o
2 o
3 p
>>> for _ in range(3):
... print("Knock, knock, knock")
... print("Penny!")
...
Knock, knock, knock
Penny!
Knock, knock, knock
Penny!
Knock, knock, knock
Penny!
直接在迭代器上循环
>>> word = "Loop"
>>> for index in range(len(word)):
... print(word[index])
获取索引
>>> word = "Loop"
>>> for index, char in enumerate(word):
... print(index, char)
...
0 L
1 o
2 o
3 p
更复杂的使用
有一个表示藏宝图的网格。宝藏以 标记。地图的中心位于坐标 (0, 0) 处,并由 .您可以按如下方式查找宝藏的坐标: oenumerate()
>>> grid = """
... .............
... .........X...
... ...X..o......
... .............
... ...........X.
... """.strip()
...
... rows = grid.split("\n")
... for row, line in enumerate(rows, start=-(len(rows) // 2)):
... for col, char in enumerate(line, start=-(len(line) // 2)):
... if char == "X":
... print(f"Treasure found at ({row}, {col})")
...
Treasure found at (-1, 3)
Treasure found at (0, -3)
Treasure found at (2, 5)
多列表访问
>>> grid = """
... .............
... .........X...
... ...X..o......
... .............
... ...........X.
... """.strip()
...
... rows = grid.split("\n")
... for row, line in enumerate(rows, start=-(len(rows) // 2)):
... for col, char in enumerate(line, start=-(len(line) // 2)):
... if char == "X":
... print(f"Treasure found at ({row}, {col})")
...
Treasure found at (-1, 3)
Treasure found at (0, -3)
Treasure found at (2, 5)
也可以使用zip函数简化上述逻辑
>>> countries = ["Norway", "Canada", "Burkina Faso"]
>>> capitals = ["Oslo", "Ottawa", "Ouagadougou"]
>>> for country, capital in zip(countries, capitals):
... print(f"The capital of {country} is {capital}")
...
The capital of Norway is Oslo
The capital of Canada is Ottawa
The capital of Burkina Faso is Ouagadougou
range的其他用法
>>> numbers = range(1, 20, 2)
>>> list(numbers)
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
>>>
>>> numbers[3] #获取 第4个数字
7
>>> numbers[-2] #获取 倒数第二个数字
17
>>> list(numbers[1:5]) #取第二个到第第六个数字,不包括第六个
[3, 5, 7, 9]
判断元素是否在range中
>>> year = 2023
>>> year in range(2000, 2100, 4)
False
>>> year = 2024
>>> year in range(2000, 2100, 4)
True
反转列表
>>> def reverse_range(rng):
... return range(
... rng.stop - rng.step,
... rng.start - rng.step,
... -rng.step,
... )
...
>>> reverse_range(range(5, 0, -1))
range(1, 6)
>>> reverse_range(reverse_range(range(5, 0, -1)))
range(5, 0, -1)