[英]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.基本上我必须得到一个可以被 7 整除但不能被 5 的倍数整除的数字列表。但是由于某种原因,当我设置条件时,它告诉我我有错误。
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...
所以有几件事...
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.因此,考虑到这一点,您基本上是在寻找 0-300 之间可以被 7 整除但不是 5 的倍数的任何数字。
Means we have a few things...意味着我们有一些事情......
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.好的,现在您不需要像示例中那样的嵌套 for 循环列表理解。 Now, you need to know "if" i is ____... So we need an if statement.
现在,您需要知道“如果” i 是____...所以我们需要一个 if 语句。
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.
当然,if 语句在我们的 for 循环内,以循环我们范围内的所有值。
Finally, if our "i" meets our criteria, then we can print all the values.最后,如果我们的“i”符合我们的标准,那么我们可以打印所有值。
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.更好的是......不,我们现在就到此为止。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.