简体   繁体   中英

Appending to List On certain Condition

I am trying to make a program, when certain condition is met the value is appended to list.

Ex:

lets say the last limit is 1000 start the count from 1 if count value is a multiple of 50, append it to a list

So the list should have numbers, 50,100,150,200...and so on..I am stuck at the third step, how would i let python know that the value is a multiple of 50

Thanks For Helping Me.

use % operator , it returns the remainder. So if a number is a multiple of 50 then it's remainder will be 0, except the case that the number itself is 0.(ie 0 divided by 50 will result in 0 as remainder)

>>> lis=[]
>>> for x in range(1,1001):
      if x%50==0:        
        lis.append(x)
>>> lis
[50, 100, 150, 200, 250, 300, 350, 400, 450, 500, 550, 600, 650, 700, 750, 800, 850, 900, 950, 1000]

If an int i is a multiple of 50, then by definition it will have zero remainder when divided by 50 - Python, like most programming languages, has a modulo operator to check exactly that - "is ia multiple of 50?" is spelled:

if i % 50 != 0:
   # i is a multiple of 50

Or equivalently:

if not i % 50:
   # i is a multiple of 50

Which of these you use depends on whether you think of this as "the remainder is zero" or as "there is no remainder" - but they will always give the same answer.

>>>a = [i for i in range(1,1001) if i%50==0]
>>>print a

or

>>>a = [i for i in range(1,1001) if not i%50]
>>>print a

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