在Python ‘For‘循环中访问索引和值

在这篇文章中,我们将学习如何在Python的for循环中访问索引值。在Python中有很多方法可以在for循环里访问索引值,但我们将主要探讨其中的四种方法。Python编程语言支持不同类型的循环,这些循环可以以不同的方式执行。

以下是一些示例,通过它们我们可以在 Python 中访问索引值:

  • 使用 range() 函数
  • 使用 enumerate() 函数
  • 使用 zip() 函数
  • 使用 itertools

使用 range() 函数访问索引和值

在这种方法中,我们使用 range() 函数来生成索引,并通过位置访问 列表 中的值。

# create a list of fruits
fruits = [‘apple‘, ‘banana‘, ‘orange‘]

print("Indices and Index value :") 

# Iterate over the indices of the list and access elements using indices
for i in range(len(fruits)):
    print(f"Index: {i}, Value: {fruits[i]}")

Output

Indices and Index value :
Index: 0, Value: apple
Index: 1, Value: banana
Index: 2, Value: orange

在Python中使用 enumerate() 访问索引和值

在这种方法中,我们在for循环中使用 enumerate() 来获取给定范围内的索引值。

# Method 2: Using enumerate
fruits = [‘apple‘, ‘banana‘, ‘orange‘]

print("Indices and values in list:") 

# Use enumerate to get both index and value in the loop
for i,fruit  in enumerate(fruits):
    print(f"Index: {i}, value: {fruit}")

Output

Indices and values in list:
Index: 0, value: apple
Index: 1, value: banana
Index: 2, value: orange

使用 zip() 访问索引值

Python中的 zip() 方法用于将索引和值一次性打包(zip),我们需要传递两个 列表,一个是索引元素的列表,另一个是值的列表。

# Method 3: Using zip 
# create a index list that stores list 
indexlist = [0, 1, 2, 3] 

  
# create a list of fruits
fruits = [‘apple‘, ‘banana‘, ‘orange‘]

print("index and values in list:") 

# get the values from indices  using zip method 
for index, value in zip(indexlist, fruits): 
    print(index, value)

Output

index and values in list:
0 apple
1 banana
2 orange

在Python中使用 itertools 访问索引和值

我们还可以将 itertools 中的 count 与 zip() 一起使用来达到类似的效果。在这个例子中,我们使用了 itertools 在 for 循环中访问索引值。

from itertools import count

# Sample list
fruits = [‘apple‘, ‘banana‘, ‘orange‘]

# Create an iterator that produces consecutive integers starting from 0
index_counter = count()

# Use zip to combine the index_counter with the list elements
for i, fruit in zip(index_counter, fruits):
    print(f"Index: {i}, Value: {fruit}")

Output

Index: 0, Value: apple
Index: 1, Value: banana
Index: 2, Value: orange
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。如需转载,请注明文章出处豆丁博客和来源网址。https://shluqu.cn/21629.html
点赞
0.00 平均评分 (0% 分数) - 0