简体   繁体   中英

I want to exclude all numbers that aren't divisible by 7 and that are not multiples of 5 in a range of numbers from (0,300)

basically I have to get a list of numbers that are divisible by 7 but not multiples of 5. but for some reason when i put the conditions it tells me i have error.

for i in [x for x in xrange(0,100) if x%7 ==0 and if x%5 !=0 ]:
    print i

I know you posted something along the lines of a list comprehension but it's a bit hard to read. So a few things...

  1. I would try writing this as a multi-line for loop before condensing it down to a list comprehension.
  2. I'm not sure why you have an 'x' in here, and 'xrange' doesn't make sense. Edit: Just realized why I don't recognize xrange and it's because I never worked with Python 2.x

So thinking through this, you are basically looking for any number from 0-300 that is divisible by 7 but is not a multiple of 5.

Means we have a few things...

  • range(0,301): Since range is not inclusive of our last value we want n+1
  • Our number, let's say "i" is both... "i%7==0" and "i%5!=0"

So let's look line-by-line

for i in range(0,301):

Okay cool, now you don't need a nested for loop list comprehension like you did in your example. Now, you need to know "if" i is ____... So we need an if statement.

if i%7==0 and i%5!=0:

See the logic? And of course that if statement is inside of our for loop to loop over all the values in our range.

Finally, if our "i" meets our criteria, then we can print all the values.

print(i)

So, our final code looks like...

for i in range(0,301):
    if (i % 7 == 0) and (i % 5 != 0):
        print(i)

Of course, there are ways you can make this more elegant, but this is the general idea.

List Comprehension:

party = [i for i in range(0,301) if i%7==0 and i%5!=0]
print(party)

That stores them all in a list so you can access them whenever. Or you can print it without assigning it of course.

Edit: The title and then what you say in the body are kind of conflicting. After reading over my own answer, I'm not completely sure if that's what you're looking for, but that is how it came across to me. Hope it helps!

Your list comprehension is incorrect. It should be something similar to:

[x for x in xrange(100) if x%5 and not x%7]

Even better (more efficient) will be something similar to

[x for x in xrange (7, 100, 7) if x%5]

Even better will be ... Nah, we'll just stop here for now.

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