Skip to main content
 首页 » 编程设计

python之我怎样才能更好地编写这些函数以使其有意义

2025年05月04日9sky-heaven

我打算编写一个函数,我可以用它来总结具有两位数的列表中的所有数字。例如:

a=[1,2,11,100,10] 
 
should return 21 since 11 and 10 of the list are having two digits 

我还希望数字的范围是 (0,1,2,...100000)

def solution(A): 
    for integer in A: 
        if integer > 9 and integer <100: 
            two_digits_array.append(integer) 
    return sum( two_digits_array ) 

我猜没问题,所以在测试中:

Example test: numbers=  [47, 1900, 1, 90, 45] 
print (solution(numbers)) 
wow it works perfectly and returns 182  

但我试过这些:

q= [1, 1000, 80, -91] 
WRONG ANSWER (got 80 expected -11) 

请问我该怎么做,为什么会失败。

请您参考如下方法:

为什么这么难?您可以简单地使用带有过滤器的生成器并将该生成器传递给 sum(..)内置的。喜欢:

def solution(A): 
    return sum(x for x in A <b>if -100 < x < -9 or 9 < x < 100</b>)

或作为 @PawełKordowski建议,使用 abs(..)使条件更优雅:

def solution(A): 
    return sum(x for x in A if <b>9 < abs(x) < 100</b>)

无需声明额外的数组(只会消耗内存)。

<expr> for <var> in <iterable> if <condition>是一个生成器:它通过应用<expr> 生成惰性 数字序列在 <var> 上对于 <iterable> 中的每个元素如果<condition>满足了。