簡體   English   中英

如何制作將列表作為輸入並返回總和的函數?

[英]How can I make function that takes a list as input and returns the sum?

我想創建一個函數,該函數將列表作為輸入並返回列表元素之間的整數、實數和復數之和。 作為列表的元素,在計算總和時排除整數、實數和復數以外的數據類型對象。

所以我這樣寫代碼

def number_sum(lst):
    total = 0
    for e in lst:
        if type(e) == int or type(e) == float or type(e) == complex:
            total += e
    return total

x1 = [1, 3, 5, 7, 9]                     # 25
x2 = ["abc", [3, 5], 3.5, 2+3j, 4.5, 10] # 20 + 3j
x3 = []                                  # 0

print(number_sum(x1))
print(number_sum(x2))
print(number_sum(x3))

但我希望我可以在輸入中輸入 x1、x2、x3 列表。 我該如何解決?

使用numbers.Number檢查值是否為數字。 從文檔:

數字層次結構的根。 如果您只想檢查參數 x 是否為數字,而不關心是什么類型,請使用 isinstance(x, Number)。

代碼

import numbers


def number_sum(lst):
    def get_numbers(l):
        """Generator that returns a flatten view a list"""
        for e in l:
            if isinstance(e, numbers.Number):
                yield e
            elif isinstance(e, (tuple, list)):
                yield from get_numbers(e)

    return sum(get_numbers(lst))


x1 = [1, 3, 5, 7, 9]
x2 = ["abc", [3, 5], 3.5, 2 + 3j, 4.5, 10]

print(number_sum(x1))
print(number_sum(x2))

輸出

25
(28+3j)

請注意,函數get_numbers是一個生成器,它使用yieldyield from來展get_numbers過濾嵌套列表。 然后將get_numbers的結果傳遞給內置函數sum以對數字進行實際求和。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM