python - 将列表或值传递给 Python 中的函数

标签 python function parameter-passing

能够将列表或值传递给函数并使其返回为

的最佳方法是什么

foo(x) :foo(x)

foo([x, y, z]) :[foo(x), foo(y), foo(z)]

只是测试输入是否是列表吗?试图访问列表元素的 try/except block ?还有别的吗?

最佳答案

使用集合来确定它是否可迭代。如果可迭代,请执行列表逻辑。如果没有,则执行您的变量逻辑

import collections

if isinstance(e, collections.Iterable) and not isinstance(e, basestring) :

正如评论中所指出的。添加逻辑以不包含字符串

关于python - 将列表或值传递给 Python 中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33675987/

相关文章:

java - 将int文字传递给在java中采用整数的方法

python - 如何在 Python 中使用类变量作为默认参数值

Python - 从字典中批量设置 pycurl 选项

python - apache - wsgi - python - 基本示例

python - 大表上的连接查询非常慢(机器 = Xeon 2.4 GHz,16 核,64 GB RAM)

python - PyQt 类是否继承自对象?

c++ - 如何识别 X 的最接近值倍数?

c - 如何使用指针返回二维数组函数?

具有返回值和返回字符串的 bash 函数

arrays - VB.NET,传递数组作为参数的两种方式是否相同?