簡體   English   中英

Python 內置 arguments 的 f(x) 大小

[英]Python Built in f(x) size of arguments

我正在努力編寫一個腳本來返回為 function 提供的 arguments 的總量,arguments 可以是字符串、元組、列表或映射字典。 在下面的腳本中,當問題要求計算每個參數時,測試示例僅返回 3,因此 id 喜歡它返回 7。非常感謝任何解釋或幫助!

'''返回序列(字符串、元組或列表)或映射(字典)的長度(項目數)。'''

編寫返回 arguments 總大小的 function。

注意:*args 表示一個變量參數列表,由一個元組表示。

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

3

我假設您想獲取所有 arguments 的長度並將長度加在一起。

這是代碼:

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

此代碼首先將 len 映射到所有 arguments ['abc', (1,), [1, 2, 3]]變為[3, 1, 3]並將它們相加。 請注意,此代碼假定所有參數都可以傳遞給len

這個解決方案更通用,因為它適用於任何可以傳遞給len的 object 以及簡單的對象,如intfloat s

def totSize(*args):

    total_length = 0
    for arg in args:
        try:
            total_length += len(arg)
        except TypeError:
            total_length += 1
    return total_length

您可以檢查元素是否是可Iterable的( strtuplelistdict等)並根據其類型累積總大小(對於不可迭代的元素,如數字,將總大小加 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]))

您可以使用len來獲取每個參數中的項目數......有時。 您還需要涵蓋參數沒有長度的情況

>>> 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
from collections import Iterable
def totSize(*args):
    return sum(len(x) if isinstance(x, Iterable) else 1 for x in args)

(感謝 L. MacKenzie 提醒Iterable

暫無
暫無

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

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