簡體   English   中英

遍歷可能是迭代器或單個元素的對象

[英]Iterate over something that may be an iterator or a single element

假設我具有以下功能:

def sum(summands)
    s = 0
    for a in summands:
        s = a + s

用戶可以使用列表sum([1, 2, 3])來調用它,但是如果您還可以直接使用數字sum(5)調用它,將會很方便。 (實際上與數字無關,只是一個簡化的示例。)

我可以發明一個功能:

def make_iterable(x):
    # returns x if x is iterable, returns [x] if x is not iterable

但是,是否有更短的內置方法使單個元素可迭代?

這個怎么樣。

def sum(summands)
    s = 0

    try:
        iter(summands)
    except TypeError:
        return summands

    for a in summands:
        s = a + s
    return s

或者,如果您想使用您提出的shell函數,則可以將try: except: make_iterablemake_iterable

Python 2.x:

def make_iterable(x):
    try:
        iter(x)
    except TypeError:
        x=[x]
    return x

Python 3.x:

def make_iterable(x):
    try: yield from x
    except TypeError: yield x

然后總結起來

def sum(summands)
    s = 0

    summands = make_iterable(summands)

    for a in summands:
        s = a + s
    return s

您可以在函數內部檢查它是否可迭代,如果不是,則將其包裝在列表中。 我相信collections.Iterable是實現此目的的好方法:

import collections

if isinstance(summands, collections.Iterable):
    tmp = summands
else:
    tmp = [summands]

您可以檢查它是否可迭代並將其設置為一個(假設它不是字符串)。 注意: sum是內置函數的名稱,因此您可能不應該使用同一名稱來命名自己的函數。 請參閱《 PEP 8-Python樣式指南》

import collections

def mysum(summand):
    if not isinstance(summand, collections.Iterable):
        summand = (summand,)
    elif isinstance(summand, str):
        raise TypeError('string argument not supported')
    s = 0
    for a in summand:
        s += a
    return s

print(mysum([1, 2, 3]))
print(mysum(42))
print(mysum("won't work"))

輸出:

6
42
Traceback (most recent call last):
  File "iterate-over-something.py", line 18, in <module>
    print(mysum("won't work"))
  File "iterate-over-something.py", line 10, in mysum
    raise TypeError('string argument not supported')
TypeError: string argument not supported

您可以測試它是列表還是整數:

if isinstance(summand, list)
    sumlist(summand)
if isinstance(summand, int)
    Sumint(summand)

然后為每種類型編寫求和函數。 或者,您可以使用列表組合將整數變成列表'summand = [x表示x在range(summand +1)中]。

這就是你所需要的

def sum(summands)
s = 0
summands = summands if isinstance(summands, list) else [summands]
for a in summands:
    s = a + s

暫無
暫無

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

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