我有一个函数应该能够将许多字符串参数作为 *args,或者将字符串列表作为参数。例如:
def getStuff(*stuff):
for thing in stuff:
print(thing)
getStuff("cat", "mouse", "dog")
getStuff(animals)
如果我以任何一种方式调用此函数,我都希望它能够产生相同的结果。我目前正在使用以下非常简单的方法,但不是最干净的代码:
def getStuff(*stuff):
if type(stuff[0]) != list:
for thing in stuff:
print(thing)
else:
for thing in stuff:
for subthing in thing:
print(subthing)
有没有简单的方法可以做到这一点?我正在寻找 Python 最佳实践。
最佳答案
在 Python 中,许多人更喜欢遵循 EAFP类型检查原则(又名 LBYL )——因为异常处理相当便宜——见 What is the EAFP principle in Python?具体this answer .
以下是如何将它应用到您的示例代码中:
def getStuff(*stuff):
try:
stuff[0].split()
except AttributeError: # List objects have no split() method.
stuff = stuff[0]
for thing in stuff:
print(thing)
getStuff("cat", "mouse", "dog")
print()
animals = ['cow', 'horse', 'pig']
getStuff(animals)
输出:
cat
mouse
dog
cow
horse
pig
关于python - 我希望一个函数能够将字符串列表或多个字符串作为参数作为 *args,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67348895/