如何在Python while in循环中找到数组中元素的索引
抱歉,但我对编程相当陌生,似乎找不到与我需要的内容相关的任何内容...
while i<size(Array):
for index, k in enumerate(Array1):
if (k==Array[i]):
print index
i=i+1
上面的代码提供了一个索引超出范围的输出... 请注意,Array1 的元素少于 Array。
我想知道如何在没有错误的情况下运行循环,并且我不太确定导致错误的原因。
谢谢你!
Sorry but I'm fairly new to programming and cannot seem to find anything that relates to what I need...
while i<size(Array):
for index, k in enumerate(Array1):
if (k==Array[i]):
print index
i=i+1
The above code presents an output that has the index out of bounds...
Note that Array1 has less elements then Array.
I'm wondering how it would be possible to run the loop without the error and I'm not really sure what is causing the error.
Thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我是一个索引,你更新它太频繁了。移动 i = i+1 的缩进以消除索引越界。
i is an index and you are updating it too often. Move the indentation of i = i+1 to get rid of the index out of bounds.
如果您只想要第一个索引(或者只有一个索引),那么您可以使用索引函数:
要获取索引列表:
If you only want the first index (or there will only be one index) then you can use the index function:
To get a list of the indices:
符来测试某个值是否在列表中:
您可以使用
in
成员资格测试运算You can test whether a value is in a list by using the
in
membership testing operator:output
看起来好像您想打印内部数组中的所有索引,其中值与输出数组中的值匹配:
输出:
如果您想收集索引,则需要列表理解:
输出:
或者可能按排序顺序:
输出:
It looks as if you want to print all indexes in the inner array where the value matches a value in the output array:
Output:
If you want to collect the indices, you a list comprehension:
Output:
Or maybe in sorted order:
Output:
如果我理解正确,您认为 i 不应该超过数组的大小,因为您有一段时间
i
i
i
i
i
i
i
i
i
i
i
i
i size(Array)
但 while 条件仅控制循环是否重复,并不能保证整个循环中 i 始终小于 size。您似乎认为这将在数组上循环一次,但因为一个循环位于另一个循环内部:循环本身将重复。
在这种情况下,i 在内部循环中为 Array1 中的每个元素递增一次,这导致它对于索引 Array 来说变得太高。
我认为你想要的是同时迭代两个列表。不要通过创建两个循环来实现这一点,您只需要一个循环。
更好的方法,但对于初学者来说可能更难理解是:
Zip 将两个列表“压缩”在一起,这使得并行迭代两个列表变得非常容易。
If I understand correctly, you are thinking that i shouldn't go above the size of Array, because you have a while
i < size(Array)
But the while condition only controls whether the loop will repeat, it does not guarantee that i will remain less then size throughout the loop.You seem to be thinking that this will loop over the arrays once, but because one loop is inside the other: the loop itself will be repeated.
In this case, i is incremented inside the inner loop once for every element in Array1, which causes it to become too high for indexing Array.
I think what you want is to iterate over both lists at the same time. Don't do this by creating two loops, you only want one loop.
A better approach, but perhaps harder to understand for a beginner is this:
Zip "zips" the two lists together which makes it really easy to iterate over both in parallel.