【问题标题】:I am not sure if i wrote my even odd while loop right [duplicate]我不确定我是否正确地写了我的偶数 while 循环 [重复]
【发布时间】:2021-05-01 04:45:58
【问题描述】:

所以问题来了:even_or_odd_all 函数将整数列表作为输入,计算并返回一个包含 True/False 的列表,表示输入列表中的每个对应数字是否为偶数。(使用 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 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}

【问题讨论】:

  • 您可以在此处尝试列表推导式,它可以为您提供一个新的布尔值列表,具体取决于您的输入列表。

标签: python-3.x math pycharm


【解决方案1】:

您只需要创建一个列表,就可以使用 for 循环遍历奇数和偶数列表,并将条件附加到列表并返回。

代码如下:

 def even_or_odd_all(even_odd):
        bool_list = []
    
        for i in even_odd:
            bool_list.append(i % 2 == 0)
        return bool_list

调用函数: even_or_odd_all([2,4,6,12,12,312,31,2312])

输出: [True, True, True, True, True, True, False, True]

【讨论】:

    【解决方案2】:

    通过列表理解,您的问题实际上是单行的:

    def even_or_odd_all(even_odd):
        return [n % 2 == 0 for n in even_odd]
    

    while 循环并不是一个很好的选择,因为您想遍历一个列表,而这总是会邀请for-construction。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-08-10
      • 2018-08-17
      • 1970-01-01
      • 2014-07-16
      • 2012-03-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多