1.range()range() 函数是 Python 中用于生成一系列数字的内置函数
range() 函数是 Python 中用于生成一系列数字的内置函数,常用于循环。它有三种常见的用法:
== 1. 单个参数==
for i in range(5):
print(i)
output:
0
1
2
3
4
2.两个参数
for i in range(2,7):
print(i)
output:
2
3
4
5
6
3.三个参数生成从 start 到 stop-1,步长为 step 的数字序列
for i in range(1, 10, 2):
print(i)
output:
1
3
5
7
9
enumerate() 函数枚举
enumerate()
函数是 Python 的一个内置函数,用于在遍历可迭代对象(如列表、元组或字符串)时获取元素的索引和值。它返回一个枚举对象,该对象生成包含索引和值的元组。以下是一些常见的用法示例:
基本用法:
fruits = ["apple", "banana", "cherry"] for index, value in enumerate(fruits): print(index, value)
输出:
0 apple 1 banana 2 cherry
指定起始索引:
你可以通过start
参数指定索引的起始值:fruits = ["apple", "banana", "cherry"] for index, value in enumerate(fruits, start=1): print(index, value)
输出:
1 apple 2 banana 3 cherry
与其他数据结构一起使用:
enumerate()
可以与元组、字符串等其他可迭代对象一起使用:# 使用元组 fruits = ("apple", "banana", "cherry") for index, value in enumerate(fruits): print(index, value) # 使用字符串 text = "hello" for index, char in enumerate(text): print(index, char)
输出:
0 apple 1 banana 2 cherry 0 h 1 e 2 l 3 l 4 o
enumerate()
函数非常有用,特别是在需要同时访问元素及其索引的情况下¹²³。