【发布时间】:2019-04-03 16:26:11
【问题描述】:
这真的是最 Pythonic 的方式来制作一个可以接受一个可迭代或任意数量的参数并对每个参数执行某些操作的函数吗?
from collections.abc import Iterable
def for_each(*args):
"""Take any number of arguments or an iterable and do something with them.
Shouldn't throw an error or print anything when no arguments are given.
"""
if (len(args) == 1
and isinstance(args[0], Iterable)
and not isinstance(args[0], str)):
# Is this really the most Pythonic way to do this?
args = args[0]
for arg in args:
# heavily simplified
print("done", arg)
for_each(1, 2)
for_each(['foo', 'bar'])
for_each((3, 4, 5))
for_each() # does essentially nothing, like it should
for_each("string") # don't loop over the characters
for_each(6)
输出:
done 1 done 2 done foo done bar done 3 done 4 done 5 done string done 6
我得到了这个有效的答案from here,但由于我实际上是在寻找一种更清洁的方法来做到这一点,所以我提出了这个新问题。
这可行,但在我看来,检查非常难看,我希望有更简单、更清洁的方法来实现这一点。 输出应该保持不变。
【问题讨论】:
标签: python python-3.x function arguments