[英]Python 3 - Print numbers from a list whose square value is evenly divisible by 8
I'm currently working on a question to determine if a square value in a list is evenly divisible by 8, and then print it out from the list if this is the case.我目前正在研究一个问题,以确定列表中的平方值是否可以被 8 整除,如果是这种情况,然后将其从列表中打印出来。 So for example I can have this list:所以例如我可以有这个列表:
list1 = [2, 4, 6, 8, 10, 12]
4 squared = 16, which is divisible evenly by 8. 4 平方 = 16,可被 8 整除。
8 square = 64, which is divisible by 8, etc. 8 平方 = 64,可以被 8 整除,以此类推。
So, the program has to print the square values that are divisible by 8. I have realised, I have to use the print()
function as well as "for" and "in" most likely since its a loop type question.因此,程序必须打印可被 8 整除的平方值。我意识到,我必须使用print()
函数以及“for”和“in”,因为它很可能是一个循环类型的问题。
As a reference, here is the original question:作为参考,这是原始问题:
Print each number in a list whose square is evenly divisible by 8.打印一个列表中的每个数字,其平方可以被 8 整除。
For example, if list is例如,如果列表是
[2, 3, 4, 5, 6, 7, 8, 9]
, then the number 4 is one number that should be printed because 4 squared is 16 and 16 is evenly divisible by 8. Test your code module with two test lists. ,那么数字 4 是一个应该打印的数字,因为 4 的平方是 16 并且 16 可以被 8 整除。用两个测试列表测试您的代码模块。
Observe that if the square of x
is divisible by 8, then x
is divisible by 4
, so:观察,如果x
的平方可以被 8 整除,那么x
可以被4
整除,所以:
list1 = [2, 4, 6, 8, 10, 12]
print [x for x in list1 if x & 3 == 0]
num_list = [2, 3, 4, 5, 6, 7, 8, 9]
First you iterate over the list.首先,您遍历列表。 Use the for
loop for it.使用for
循环。 Put your if condition in there if (x * x) % 8 == 0 then print the number
:把你的 if 条件放在那里if (x * x) % 8 == 0 then print the number
:
for num in num_list:
if (num * num) % 8 == 0:
print(num)
The key idea is finding the square, for it you use num * num
.关键思想是找到正方形,因为你使用num * num
。
To check if a number x
is divisible by 8 you use x % 8 == 0
要检查数字x
是否可以被 8 整除,请使用x % 8 == 0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.