如何在列表python中对数字求和

Bob*_*y B 1 python sum

因此,我正在玩并尝试仅在它是特定用户输入术语时对类似术语求和.例如在列表中 L = [1,2,2,3,4]然后我说我希望所有项的总和为2,因此2显示两次并且我知道2+2=4它将返回4.

到目前为止,我觉得这比我要做的要容易得多:

def main():
    L = eval(input("Please enter the list")
    num = eval(input('Enter the number that has like terms'))
    sloppyway = []
    for nums in L:
        if nums == num:
            sloppyway.append(nums)
    return (sum(sloppyway))
Run Code Online (Sandbox Code Playgroud)

我认为这样可行,但我觉得有一种更时尚,更优雅的方式.有什么建议?

Kas*_*mvd 6

您可以使用sum带有生成器表达式的函数,如下所示:

>>> L = [1,2,2,3,4] 
>>> num=2
>>> sum(i for i in L if i==num)
4
Run Code Online (Sandbox Code Playgroud)

或者作为一种效率较低的方式,您可以使用filter功能:

>>> sum(filter(lambda x :x==2,L))
4
Run Code Online (Sandbox Code Playgroud)

但请注意,如果您的病情更复杂,这可能会有所帮助!