我有一个函数具有任意数量的参数,并且需要在这些参数是数字或可以转换为数字时添加这些参数。例子:
def object_sum(*args):
pass
print(object_sum(3, 'sun', '5', ['5', 'earth'], (5, '5')))
#Would print 23
假设您想要捕获嵌套的整数,请执行:
from collections.abc import Iterable
def object_sum(*args):
def flatten(l):
# https://stackoverflow.com/a/2158532/4001592
for el in l:
if isinstance(el, Iterable) and not isinstance(el, (str, bytes)):
yield from flatten(el)
else:
try:
yield int(el)
except ValueError:
yield 0
return sum(flatten(args))
print(object_sum(3, 'sun', '5', ['5', 'earth'], (5, '5')))
23
测试参数是否为列表或类似类型,如果是,递归到它,如果不是,尝试将其转换为整数:
def object_sum(*args):
result = 0
for arg in args:
arg_type = type(arg)
if arg_type in (list, tuple, set, range):
result += object_sum(*arg) # The asterisk is important - without it, the recursively called function would again call itself, and we'd get a RecursionError
else:
try:
result += int(arg) # Try to convert to int
except ValueError:
pass # arg is not convertable, skip it
return result
print(object_sum(3, 'sun', '5', ['5', 'earth'], (5, '5')))
输出:
23