python - 我希望一个函数能够将字符串列表或多个字符串作为参数作为 *args

标签 python function arguments args keyword-argument

我有一个函数应该能够将许多字符串参数作为 *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/

相关文章:

Python/从字符串中删除特殊字符

C++:整数数组[a][b][c] = {0};没有将所有值都设置为 0。该指令是错误的还是我的输出函数有问题?

r - 为什么我构建的 R 函数会产生错误的输出?

function - 球体不显示|数学

arguments - 为什么这个没有参数的 TCL proc 不起作用?

python - 使用 Popen 打开进程并获取 PID

python - 如何在 pytest 中运行标记为 skip 的测试

java - 如何将参数传递给线程

Python 代码作为参数

Python Pandas,将字符串列导出到 Excel 文件中