Python 3.x 我不确定我写的偶数-奇数while循环是否正确
问题是:偶数或奇数all函数将整数列表作为输入,计算并返回一个包含真/假的列表,表示输入列表中的每个对应数字是否为偶数。(使用While循环) 这是我的代码:Python 3.x 我不确定我写的偶数-奇数while循环是否正确,python-3.x,math,pycharm,Python 3.x,Math,Pycharm,问题是:偶数或奇数all函数将整数列表作为输入,计算并返回一个包含真/假的列表,表示输入列表中的每个对应数字是否为偶数。(使用While循环) 这是我的代码: def even_or_odd_all(even_odd): #input is a list of integers #output is a list of boolean values (which depends on if the number is even or odd) #So this function is s
def even_or_odd_all(even_odd):
#input is a list of integers
#output is a list of boolean values (which depends on if the number is even or odd)
#So this function is supposed to take in a list and return a list with booleans depending on if therye even or odd
# i guess i needa use a while loop
while True:
i in (range(len(even_odd)))
even_odd = []
if (i % 2) == 0:
even_odd.append(i % 2 == 0)
return [i]
i = False
然而,我也不断得到这个错误
{ Traceback (most recent call last):
File "<input>", line 1, in <module>
File "<input>", line 7, in even_or_odd_all
UnboundLocalError: local variable 'i' referenced before assignment}
{回溯(最近一次呼叫最后一次):
文件“”,第1行,在
文件“”,第7行,偶数或奇数
UnboundLocalError:赋值前引用的局部变量“i”}
您只需创建一个列表,就可以使用for循环遍历奇数和偶数列表,并将条件附加到列表中并返回它
代码如下:
def even_or_odd_all(even_odd):
bool_list = []
for i in even_odd:
bool_list.append(i % 2 == 0)
return bool_list
调用函数:
偶数或奇数全部([2,4,6,12,12312,312312312])
输出:
[真、真、真、真、真、真、假、真]
您只需创建一个列表,就可以使用for循环遍历奇数和偶数列表,并将条件附加到列表中并返回它
代码如下:
def even_or_odd_all(even_odd):
bool_list = []
for i in even_odd:
bool_list.append(i % 2 == 0)
return bool_list
调用函数:
偶数或奇数全部([2,4,6,12,12312,312312312])
输出:
[真、真、真、真、真、真、假、真]
通过列表理解,您的问题实际上是一行:
def偶数或奇数(偶数/奇数):
返回[n%2==0,表示n为奇偶]
while循环并不是一个很好的选择,因为你想在列表上迭代,这总是需要一个
的结构。通过列表理解,你的问题实际上是一行:
def偶数或奇数(偶数/奇数):
返回[n%2==0,表示n为奇偶]
while循环并不是一个好的选择,因为你想在列表上迭代,这总是需要一个来进行-构造。你可以在这里尝试列表理解,根据你的输入列表,它可以给你一个新的布尔列表。你可以在这里尝试列表理解,它可以给你一个新的布尔列表,取决于您的输入列表。