简体   繁体   中英

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.

Hint: try iterating over 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:

>>> 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. Because 3 is first value in x which is greater that 2.7 , above code returned the index of 3 which is 1 .

If it is must for you to use range(len(x)) , then you can update above logic (it is entirely unnecessary though) as:

>>> 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 . Instead, you need to use it as an index and compare against the corresponding value of x list. Also, you are using your temporary variable as x while iterating in for loop, which is same as variable holding your list. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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