gpt4 book ai didi

python - 索引值 16 的 list.index(value) 的值设置为 9

转载 作者:太空宇宙 更新时间:2023-11-04 10:01:05 24 4
gpt4 key购买 nike

我有一个 list

array_list=[-37, -36, -19, -99, 29, 20, 3, -7, -64, 84, 36, 62, 26, -76, 55, -24, 84, 49, -65, 41]

当我尝试使用以下代码遍历打印索引和与索引关联的值时

for value in array_list:
print(array_list.index(value), array_list[array_list.index(value)])

我得到以下输出:

0 -37
1 -36
2 -19
3 -99
4 29
5 20
6 3
7 -7
8 -64
9 84
10 36
11 62
12 26
13 -76
14 55
15 -24
9 84 # I want the value as 16 instead of 9 (position of 84 in list)
17 49
18 -65
19 41

在索引 16 处,它给我的索引值为 9。我不确定为什么它应该给我 16 作为索引值。

我该如何解决这个问题?

最佳答案

list.index(..) 返回 list 中元素第一次出现的值。例如:

>>> my_list = [1,2,3,1,2,5]
>>> [(i, my_list.index(i)) for i in my_list]
[(1, 0), (2, 1), (3, 2), (1, 0), (2, 1), (5, 5)]

# Here, 0th index element is the number
# 1st index element is the first occurrence of number

如果你想在迭代过程中得到元素的位置,你应该使用enumerate用于迭代。例如:

>>> [(i, n) for n, i in enumerate(my_list)]
[(1, 0), (2, 1), (3, 2), (1, 3), (2, 4), (5, 5)]

# Here, 0th index element is the number
# 1st index element is the position in the list

您可以引用Python's List Document ,它说:

list.index(x)

Return the index in the list of the first item whose value is x. It is an error if there is no such item.

关于python - 索引值 16 的 list.index(value) 的值设置为 9,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43525017/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com