【问题标题】:How to detect and convert a no-iterable parameter to iterable one如何检测不可迭代参数并将其转换为可迭代参数
【发布时间】:2021-07-21 10:59:24
【问题描述】:

我有一个 Python 函数,它接受类似向量的参数,但我希望如果有人使用不可迭代参数调用该函数,该函数会接受并将其视为单元素向量。

例如,返回向量大小的函数:

def longitud(v):
    return len(v)

y = [1,2]
print(longitud(y))  # it will return 2, OK

x = 1
print(longitud(x))  # ERROR

它会产生错误,因为x 是不可迭代的。我希望 longitud 函数可以毫无问题地接受这两个参数,并且在第二种情况下,将 x 视为一个元素向量。有什么优雅的方法可以做到这一点?

【问题讨论】:

    标签: python-3.x iterable


    【解决方案1】:

    你想要这个吗?

    def longitud(*v):
        return len(v)
    
    y = [1,2]
    print(longitud(*y))  # it will return 2, OK
    
    x = 1
    print(longitud(x))  # No ERROR
    

    Alternative(检查参数是否可迭代,否则返回1) -

    from collections.abc import Iterable
    
    def longitud(v):
        if isinstance(v, Iterable):
            return len(v)
        return 1
        
    
    y = [1,2]
    print(longitud(y))  # it will return 2, OK
    
    x = 1
    print(longitud(x))  # NO ERROR
    

    【讨论】:

    • 第二个选项适合我的问题,因为该函数接受任何向量或单个元素。谢谢!
    • 没问题 :) @AliRojas
    猜你喜欢
    • 2022-11-13
    • 2020-09-07
    • 1970-01-01
    • 2021-04-21
    • 2012-05-07
    • 2016-12-13
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    相关资源
    最近更新 更多