enumerate:枚举,对于一个可迭代的(iterable)/可遍历的对象(如列表、字符串),enumerate将其组成一个索引序列,利用它可以同时获得索引和值。 li = ['alex','银角','女神','egon','太白'] for i in enumerate(li): print(i) for index,name in enumerate(li,1): print(index,name) for index, name in...
3. 使用enumerate()函数 在遍历列表时,有时候我们需要知道元素的索引。此时可以使用`enumerate()`函数,它会返回一个包含索引和值的元组: ```python names = ["Alice", "Bob", "Charlie"] for index, name in enumerate(names): print(f"Index: {index}, Name: {name}") ``` 4. 使用zip()函数 当...
使用enumerate遍历列表 fruits = ["apple", "banana", "cherry"] for index, fruit in enumerate(fruits): print(f"Index: {index}, Fruit: {fruit}") 使用enumerate遍历字典 person = {"name": "Alice", "age": 30, "city": "New York"} for key, value in person.items(): print(f"Key: {k...
enumerate:枚举,对于一个可迭代的(iterable)/可遍历的对象(如列表、字符串),enumerate将其组成一个索引序列,利用它可以同时获得索引和值。 li = ['alex','银角','女神','egon','太白']foriinenumerate(li):print(i)forindex,nameinenumerate(li,1):print(index,name)forindex, nameinenumerate(li, 100):...
print(f"Index: {index}, Fruit: {fruit}") 使用enumerate遍历字典 person = {"name": "Alice", "age": 30, "city": "New York"} for key, value in person.items(): print(f"Key: {key}, Value: {value}") 总结 for循环和enumerate函数是在Python中迭代集合元素时的两种不同方式。for循环适用...
使用enumerate遍历列表 复制 fruits = ["apple", "banana", "cherry"] for index, fruit in enumerate(fruits): print(f"Index: {index}, Fruit: {fruit}") 1. 2. 3. 4. 使用enumerate遍历字典 复制 person = {"name": "Alice", "age": 30, "city": "New York"} ...
enumerate还可以接收第二个参数,用于指定索引起始值,如: list1=["这","是","一个","测试"]forindex,iteminenumerate(list1,1):print index,item>>>1这2是3一个4测试 补充 如果要统计文件的行数,可以这样写: count=len(open(filepath,'r').readlines()) ...
print(obj["name"] + ":" + obj["size"]) 4)for+enumerate()遍历序列的索引下标和序列对象 平时我们用for循环要拿每次循环的下标index,要定义个对象,比如: index = 0 for x in range(5): print("第" + str(x + 1) + "个数据-->" + str(x)) ...
for index, value in enumerate(my_list): print(index, value) 1. 2. 3. 输出结果: 0 apple 1 banana 2 orange 1. 2. 3. 在这个例子中,我们创建了一个列表my_list,并使用for循环和enumerate()函数来遍历该列表中的所有元素。在循环中,我们使用变量index和value来保存当前元素的索引和值。