python - 迭代可能是迭代器或单个元素的东西

标签 python python-3.x

假设我有以下功能:

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_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

然后用sum来调用

def sum(summands)
    s = 0

    summands = make_iterable(summands)

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

关于python - 迭代可能是迭代器或单个元素的东西,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36750167/

相关文章:

Python:与复杂的数据仓库交互

python - 无法使用 PyQt5 在父 QWidget 中添加背景图像?

python copy.deepcopy 列表看起来很浅

python - Python 中的多层 .gdb 文件?

python - 将科学计数法转换为人类可读的 float

python - 使用 python 将日期时间转换为整数以进行 NVD3 绘图

python - 堆叠式 filter() 调用的奇怪行为

excel - 根据单元格值将 pandas DataFrame 导出到 Excel

python - splinter 的 Pandas 安装

python - 如何使用 python 3.x 执行多项式加法和乘法?