如何在 Python 的 for 循环中访问索引
在本文中,我们将讨论在Python为循环访问索引。
我们可以使用以下方法访问索引:
- 使用索引元素
- 使用枚举()
- 使用列表推导式
- 使用 zip()
索引元素用于表示元素在列表中的位置。这里我们通过元素列表访问索引
使用索引元素
在这里,我们使用迭代器变量来迭代列表。
Python3
# create a list of subjects
data = ["java", "python", "HTML", "PHP"]
print("Indices in the list:")
# display indices in the list
for i in range(len(data)):
print(i)
print("Index values in the list:")
# display each index value in the list
for i in range(len(data)):
print(data[i])
Python
# create a list of subjects
data = ["java", "python", "HTML", "PHP"]
print("Indices and values in list:")
# get the indices and values using enumerate method
for i in enumerate(data):
print(i)
Python3
# create a list of subjects
data = ["java", "python", "HTML", "PHP"]
print("Indices in list:")
# get the indices using list comphrension method
print([i for i in range(len(data))])
print("values in list:")
# get the values from indices using list
# comphrension method
print([data[i] for i in range(len(data))])
Python3
# create a index list that stores list
indexlist = [0, 1, 2, 3]
# create a list of subjects
data = ["java", "python", "HTML", "PHP"]
print("index and values in list:")
# get the values from indices using zip method
for index, value in zip(indexlist, data):
print(index, value)
输出:
Indices in the list:
0
1
2
3
Index values in the list:
java
python
HTML
PHP
使用 enumerate() 方法
此方法用于 for 循环,用于获取索引以及范围内的相应元素。
Python
# create a list of subjects
data = ["java", "python", "HTML", "PHP"]
print("Indices and values in list:")
# get the indices and values using enumerate method
for i in enumerate(data):
print(i)
输出:
Indices and values in list:
(0, 'java')
(1, 'python')
(2, 'HTML')
(3, 'PHP')
使用列表理解方法
这将创建一个索引列表,然后给出索引和索引值。
蟒蛇3
# create a list of subjects
data = ["java", "python", "HTML", "PHP"]
print("Indices in list:")
# get the indices using list comphrension method
print([i for i in range(len(data))])
print("values in list:")
# get the values from indices using list
# comphrension method
print([data[i] for i in range(len(data))])
输出:
Indices in list:
[0, 1, 2, 3]
values in list:
['java', 'python', 'HTML', 'PHP']
使用 zip() 方法
zip方法用于一次压缩索引和值,我们必须传递两个列表,一个列表是索引元素,另一个列表是元素
蟒蛇3
# create a index list that stores list
indexlist = [0, 1, 2, 3]
# create a list of subjects
data = ["java", "python", "HTML", "PHP"]
print("index and values in list:")
# get the values from indices using zip method
for index, value in zip(indexlist, data):
print(index, value)
输出:
index and values in list:
0 java
1 python
2 HTML
3 PHP