Python内置参数的f(x)大小

问题描述 投票:1回答:5

我正在努力编写一个脚本,该脚本返回为该函数提供的参数总数,这些参数可以是字符串,元组,列表或映射字典。在下面的脚本中,当问题要求对每个参数进行计数时,测试示例仅返回3,因此id像它返回7。非常感谢任何解释或帮助!

'''返回序列的长度(项目数)(字符串,元组或列表)或映射(字典)。'''

编写一个返回参数总大小的函数。

注:* args表示变量参数列表,由元组表示。

def totSize(*args): 
    return len(args)
print(totSize('abc', (1,), [1,2,3]))

3

python python-3.x function arguments built-in
5个回答
2
投票
这里是代码:

def totSize(*args): return sum(map(len, args))

此代码首先将len映射到所有参数['abc', (1,), [1, 2, 3]]变为[3, 1, 3],然后将它们求和。请注意,此代码假定所有的argumens都可以传递给len


2
投票
def totSize(*args): total_length = 0 for arg in args: try: total_length += len(arg) except TypeError: total_length += 1 return total_length

1
投票
例如:

from collections import Iterable def totSize(*args): total_size = 0 for i in args: if isinstance(i, Iterable): total_size += len(i) else: total_size += 1 return total_size print(totSize('abc', (1,), [1, 2, 3]))


0
投票
>>> def totSize(*args): ... count = 0 ... for arg in args: ... try: ... count += len(arg) ... except TypeError: ... count += 1 ... return count ... >>> print(totSize('abc', (1,), [1,2,3])) 7

0
投票
((感谢L. MacKenzie提醒Iterable
© www.soinside.com 2019 - 2024. All rights reserved.