简体   繁体   English

找到 x 中大于 0.999 的第一个值的索引

[英]find the index of the first value in x that is greater than 0.999

I am confused with this question, how can I solve this?, I try something like this below without index how can I combine them together?我对这个问题感到困惑,我该如何解决这个问题?,我在下面尝试这样的事情,没有索引如何将它们组合在一起? Thank you谢谢

Q.Try to find the index of the first value in x that is greater than 0.999 using a for loop and break. Q.尝试使用 for 循环和 break 查找 x 中大于 0.999 的第一个值的索引。

Hint: try iterating over range(len(x)).提示:尝试迭代 range(len(x))。

for x in range(len(x)):
    if x > 0.999:
        break

print("The answer is", x)```

Better way to achieve this is usingnext() and enumerate() with generator expression as:更好的方法是使用带有生成器表达式next()enumerate()

>>> x = [1, 3, 1.5, 7, 13, 9.2, 19]
>>> num = 2.7

>>> next(i for i, e in enumerate(x) if e > num)
1

enumerate() returns the index along with element while iterating over the list.enumerate()在遍历列表时返回索引和元素。 Because 3 is first value in x which is greater that 2.7 , above code returned the index of 3 which is 1 .因为3x中大于2.7的第一个值,所以上面的代码返回了3的索引,即1

If it is must for you to use range(len(x)) , then you can update above logic (it is entirely unnecessary though) as:如果您必须使用range(len(x)) ,那么您可以将上述逻辑更新为:

>>> next(i for i in range(len(x)) if x[i] > num)
1

Issue with your code is that while iterating the list, you are checking the value returned by range() to make a comparison 0.999 .您的代码的问题是,在迭代列表时,您正在检查range()返回的值以进行比较0.999 Instead, you need to use it as an index and compare against the corresponding value of x list.相反,您需要将其用作索引并与x列表的相应值进行比较。 Also, you are using your temporary variable as x while iterating in for loop, which is same as variable holding your list.此外,您在for循环中迭代时将临时变量用作x ,这与保存列表的变量相同。 You can fix your code as:您可以将代码修复为:

for i in range(len(x)):
    if x[i] > 0.999:
        break

If you really want you use a for loop with a break, you can use enumerate.如果您真的希望使用带中断的 for 循环,则可以使用 enumerate。

x = [0, 0.3, 0.6, 0.8, 1, 0.4, 0.5, 6]

for i, num in enumerate(x):
    if num > 0.999:
        break
print("The answer is", i)
#The answer is 4

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

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