【问题标题】:How to solve this TypeError in lambda functions? [duplicate]如何解决 lambda 函数中的这个 TypeError? [复制]
【发布时间】:2021-12-10 19:55:45
【问题描述】:

在字符串格式化期间出现并非所有参数都转换的错误

def even_odd_lambda(list_object):
  
    #odd_ctr = list(filter(lambda x: (x%2 != 0) , list_1))
    #even_ctr = list(filter(lambda x: (x%2 == 0) , list_1))
    
    odd_ctr = len(list(filter(lambda x: (x%2 != 0) , list_object)))
    even_ctr = len(list(filter(lambda x: (x%2 == 0) , list_object)))

    return [odd_ctr, even_ctr] 


if __name__ == '__main__':
  
    a=input("Add list elements seperated by space ").split(' ')

    
    
    output = even_odd_lambda(a)
    print("\nNumber of even numbers in the above array: ", output[1])
    print("\nNumber of odd numbers in the above array: ", output[0])  

【问题讨论】:

标签: python python-3.x


【解决方案1】:

把你的输入变成整数:

a = [*map(int, input("Add list elements seperated by space ").split())]

另外,您应该避免仅仅为了测量它们的长度而构建列表。我也会避免使用map/filterlambda;它总是比生成器或理解器更长且可读性更低。比较:

list(filter(lambda x: (x%2 != 0) , list_object))
[x for x in list_object if x%2 != 0]

例如,您可以将sum 与生成器一起使用,以减少内存占用并提高可读性:

def even_odd_lambda(list_object):
    odd_ctr = sum(x%2 for x in list_object)
    even_ctr = sum(not x%2 for x in list_object) 
    return [odd_ctr, even_ctr] 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-21
    • 2018-08-21
    • 1970-01-01
    • 1970-01-01
    • 2021-10-14
    • 2020-06-12
    • 1970-01-01
    • 2022-07-01
    相关资源
    最近更新 更多