【问题标题】:List of natural numbers = > returns booleans自然数列表 = > 返回布尔值
【发布时间】:2021-11-13 12:56:05
【问题描述】:

编写一个接收自然数列表作为参数并返回布尔值列表的函数。如果列表中的数字是偶数,那么我们将在最终列表中添加 True;对于奇数,我们添加 False。

我的尝试:

def my_int_list(list):
    new_list= []
    for num in list:
        if num % 2 == 0:
            num = True
            new_list.append(num)
        elif num % 2 != 0:
            num = False
            new_list.append(num)



my_list=[2,5,8]

print(my_int_list(my_list))

【问题讨论】:

  • print(list(map(lambda x: not x % 2, my_list)))

标签: list integer boolean


【解决方案1】:

你不应该调用一个变量list,因为它是一个python内置函数,你也忘了写return。

def my_int_list(listt):
    new_list= []
    for num in listt:
        if num % 2:              # If there is 1 in reminder (more Pythonic)
            num = False
            new_list.append(num)
        else:                    # No need to Check reminder is 0?, because if reminder not 1 it always 0 (when divider is 2)
            num = True
            new_list.append(num)
    return new_list

my_list=[2,5,8]

print(my_int_list(my_list))

这里的条件 if num % 2:
仅当提醒为 0 以外的任何数字时才返回 true,
在我们的例子中,只有两个选项 0 或 1。

【讨论】:

  • 非常感谢!
【解决方案2】:

或者,这也可以

def my_int_list(my_list):
    new_list = []
    for num in my_list:
        if num % 2 == 0:
            new_list.append(True)
        elif num % 2 != 0:
            new_list.append(False)
    print(new_list)

my_list = [2, 5, 8]

my_int_list(my_list)

【讨论】:

  • 非常感谢!这比上面的方法更有效?
  • 欢迎您!我只是删除要分配为 True 或 False 的 num 变量。如果my_list 很长,效率会更高。 (=
  • 但比更高效更重要的是,它更简单易读
  • 好点@AxelB
【解决方案3】:

我能想到的最简单的解决方案是使用mapmap(fun, iter) 是一个函数,它在将给定函数应用于其中的每个项目后返回结果的映射对象(迭代器)。

例如,使用:

def my_int_list(lst):
    return list(map(even, lst))

def even(n):
    return n % 2 == 0

允许您将 int 列表作为布尔值返回:

print(my_int_list([1,2,3,4,5,6])) # -> [False, True, False, True, False, True]

【讨论】:

  • omg 看起来很简单:D. 我开始越来越喜欢 python。缺点是我没有研究过地图和许多其他肯定会使代码更短的东西。非常感谢,非常感谢!
猜你喜欢
  • 2020-02-13
  • 1970-01-01
  • 1970-01-01
  • 2013-08-18
  • 1970-01-01
  • 2013-09-10
  • 2021-10-29
  • 2013-03-11
  • 1970-01-01
相关资源
最近更新 更多