简体   繁体   中英

how to print 3 numbers greater than a specific number of a list in python?

I have written the following code which will ask for a number from the user and check the number in the list if they are greater than the user input, then it will print the next 3 numbers. I just don't understand how to implement the condition so that it prints the next 3 numbers, not all!

def main():
    number_list = [630,1015,1415,1620,1720,2000]
    a=int(input("Enter the time (as an integer):"))
    for i in number_list:
        if(i>=a):
            print(i)

if __name__ == "__main__":
    main()

I would first find the index of the first value that meets your condition (element greater than or equal to the inputted value):

user_input = int(input("Enter the time (as an integer):"))
desired_index = None
for index, val in enumerate(number_list):
    if val >= user_input:
        desired_index = index
        break

Then to print the three values including and after that position:

    print(number_list[desired_index:desired_index + 3])

Assuming that the list is sorted, you can use the built-in bisect module to find the position where the input number fits into the list. Then it's easy to print the next three numbers from the list (if there are that many):

import bisect

number_list = [630, 1015, 1415, 1620, 1720, 2000]
a = int(input("Enter the time (as an integer):"))

index = bisect.bisect(number_list, a)
print(number_list[index:(index + 3)])

Eg for input 1200 this prints [1415, 1620, 1720] .

Update your code to be:

def main():
    number_list = [630,1015,1415,1620,1720,2000]
    a=int(input("Enter the time (as an integer):"))
    i=0
    for n in number_list:
        if(n>=a):
            print(n)
            i+=1
            if i==3:break

if __name__ == "__main__":
    main()

Now run the code and see the output..

Enter the time (as an integer):1015
1015
1415
1620
>>> 

If you want to ensure that number_list is sorted, then use this sort method..

number_list.sort()

If the list is sorted, you should use binary search (eg bisect) otherwise you can print the first 3 elements of a filtered list:

print(*[n for n in number_list if n>a][:3])

for a more basic approach, you can keep track of how many numbers you've printed so far using a variable that you increase by one after printing a number and use that print counter in the condition to decide to print:

printed = 0                 # count of numbers printed so far
for n in number_list:
    if printed<3 and n>a:   # only print first 3 that are eligible
        print(n)
        printed += 1        # track number of numbers printed

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