简体   繁体   中英

Using a for-loop inside a while-loop

I'm trying to accomplish the following:

Go through a list and select all even numbers but stop when you have 15 numbers. To achieve this I thought of using the following:

nums = np.random.randint(1,100,50) # List of 50 numbers between 1 and 100

x = 0                              # variable to incriment
number = []                        # List to store even number
while x < 16:                       
  for num in nums:                 # Select each number in nums list
    if x%2 ==0:                    # Check if even
      number.append(num)           # Append even number to list
  x+=1                             # increment counter

but I get a list of length 400 and the counter ( x ) for 16.

What am I doing wrong?

The nested for loop means the while loop condition doesn't get checked until the entire list has been looped over. I'd suggest get rid of the while loop and just use break to control the stopping condition.

number = []
for num in nums:
    if num%2 == 0:
        number.append(num)
    if len(number) == 15:
        break
for num in nums:
    if x%2 ==0:
      number.append(num)

This part of your code will always append the even numbers in the list nums to the list number , correct?

And now, you just repeat this 16 times over by wrapping it in the

x = 0
while x < 16
    ...
    x += 1

Instead of this, you can just do

nums = np.random.randint(1,100,50) # List of 50 numbers between 1 and 100

x = 0
number = []
while len(number) < 15:                       
  for num in nums:
    if x%2 ==0:
      number.append(num)
    if len(number) < 15:
       break

or something similar

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