简体   繁体   English

for 循环 python 中的 enumerate() 问题

[英]troubles with enumerate() in for loop python

I have a list that contains indices and a list that contains values.我有一个包含索引的列表和一个包含值的列表。 I want to check, whether the value at the given position of the index is bigger or smaller than the value that is at the index-1 position in the list.我想检查索引的给定 position 处的值是否大于或小于列表中索引 1 position 处的值。 I then want my function to return the index of the value that is smaller - so either the input index or the input-index-1.然后我希望我的 function 返回较小值的索引 - 因此输入索引或输入索引 1。 For testing purposes I have created these:出于测试目的,我创建了这些:

indices = [2,5,8,11] 
values = [3,10,15,4,20,30,24,11,10,2,12,8,7] 
my_list = []

I set up a for-loop that does almost what I want but it appends the value itself, not it's index.我设置了一个 for 循环,几乎可以满足我的要求,但它附加了值本身,而不是索引。 It looks like this:它看起来像这样:

for i in indices:
    if values[i] > values[i-1]:
        my_list.append(values[i-1])
    else: 
        my_list.append(values[i])

Which gives the output这给出了 output

my_list = [10, 20, 10, 8]

I then tried using enumerate for this purpose but it returns an error.然后我尝试为此目的使用枚举,但它返回一个错误。

my_list1 = []        


for i,x in enumerate(indices):
    if values[i] > values[i-1]:
        my_list1.append(indices[x-1])
    else: 
        my_list1.append(indices[x])

the wanted output would be:想要的 output 将是:

my_list1 = [1,4,8,11] 

You were close, simply use i instead of values[i] to append the index:你很接近,只需使用i而不是values[i]到 append 索引:

for i in indices:
    if values[i] > values[i-1]:
        my_list.append(i-1)
    else: 
        my_list.append(i)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM