简体   繁体   中英

i have this list and my for loop that only show odd numbers of list but i want it show only 5 first odd number and if there is not 5 show all of them

num_list = [422, 136, 524, 85, 96, 719, 85, 92, 10, 17, 312, 542, 87, 23, 86, 191, 116, 35, 173, 45, 149, 59, 84, 69, 113, 166]

for items in num_list: if items % 2:= 0: print(items)

If I understood your question correctly, you can get what you want by adding a counter like this:

num_list = [422, 136, 524, 85, 96, 719, 85, 92, 10, 17, 312, 542, 87, 23, 86, 191, 116, 35, 173, 45, 149, 59, 84, 69, 113, 166]

counter = 0

for num in num_list:
    if num % 2 != 0 and counter < 5:
        print(num)
        counter += 1

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