简体   繁体   English

在枚举 for 循环中按索引访问值

[英]Accessing a value by index in enumerate for-loop

I'm trying to access a previous value (by index) in a for loop.我试图在 for 循环中访问以前的值(按索引)。 So I have a condition where I want to compare the value of i to i-1, but don't think I'm doing this correctly:所以我有一个条件,我想将 i 的值与 i-1 进行比较,但不要认为我这样做是正确的:

for i, f in enumerate(df[col1]):
  if f[i] < f[i-1]:
      do something

So in the above code I would try to compare df[col1][1] to df[col][0].所以在上面的代码中,我会尝试比较 df[col1][1] 和 df[col][0]。 Completely hypothetical by the way.顺便说一句,完全是假设的。 I just need to figure out the correct way to access values by index for in enumerate.我只需要找出在枚举中按索引访问值的正确方法。 Thanks谢谢

If you want to simply access the column's element from its index, you can simply do and or try this:如果你想简单地从它的索引访问列的元素,你可以简单地做和/或试试这个:

for i, f in enumerate(df['col1']):
   if df['col1'][i] < df['col1'][i - 1]:
       # do something you desire

Tell me if it works.告诉我它是否有效。

Everything looks good so far.到目前为止一切看起来都很好。 If you were to use more descriptive names it will make it easier to understand.如果您要使用更具描述性的名称,它将更容易理解。 With enumerate, you are declaring it correctly, and ordering your variables well.使用枚举,您可以正确声明它,并且可以很好地排序您的变量。 The only thing I see will come up is when you use [i-1] to index your list/dictionary.我唯一看到的是当你使用 [i-1] 来索引你的列表/字典时。 enumerate() begins it's count at 0, so you will end up with a negative index, and it will raise an error. enumerate() 从 0 开始计数,因此您最终会得到一个负索引,并且会引发错误。 You can instead use "for i, f in enumerate(df[col1], 1). The second param is the starting key it will use when enumerating over each object. Let me know how that works for you!您可以改为使用“for i, f in enumerate(df[col1], 1)。第二个参数是在枚举每个 object 时将使用的起始键。让我知道它如何为您工作!

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

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