【问题标题】:If statement on whether one string, or list of strings [duplicate]If语句是一个字符串还是字符串列表[重复]
【发布时间】:2017-06-01 21:08:34
【问题描述】:

我有以下功能。理想情况下,我希望将单个字符串或字符串列表作为输入传递。无论哪种情况,我都需要使用 .upper 。但是,当只传递一个字符串时,迭代器会遍历每个字符。我怎样才能有一个 if 语句来测试是字符串列表还是单个字符串? (我似乎无法避免字符串的可迭代性)

def runthis(stringinput):

    for t in stringinput:
        t = t.upper()

【问题讨论】:

  • 因此,即使stringinput 是字符串列表,您的代码也不会修改它。
  • 总是接受可能只包含一个字符串的字符串列表似乎更好。让调用者传递一个未列出的字符串有什么价值?

标签: python


【解决方案1】:

使用isinstance检查类型。

def runthis(stringinput):
    if isinstance(stringinput, list):
        for t in stringinput:
            t = t.upper()
            # Some other code should probably be here.
    elif isinstance(stringinput, basestring):
        t = t.upper()
        # Some other code perhaps as well.
    else:
        raise Exception("Unknown type.")

在 Python 3 中使用 str 而不是 basestring

【讨论】:

  • 谢谢!效果很好
【解决方案2】:

您可以像这样使用type() 函数:

if type(stringinput) is list:
    #Your list code
elif type(stringinput) is str:
    #Your string code
else:
    #stringinput isn't a list or a string, throw an error

【讨论】:

    【解决方案3】:

    您可以使用isinstance() 来检查您的函数arg 是否属于list 类型:

    def to_upper(arg):
        if isinstance(arg, list):
            return [item.upper() for item in arg]  # This is called list comprehension
        else:
            return arg.upper()
    

    【讨论】:

      【解决方案4】:

      一种方法是显式检查参数是列表还是字符串,并在条件子句中以不同方式处理。

      我认为可能更好的替代方法(如果它适合您的用例)可能如下:

      def runthis(*stringinput):
          for t in stringinput:
              t = t.upper()
              print(t)
          print()
      
      runthis("test") # TEST
      runthis("another", "test")  # ANOTHER TEST
      runthis(*["one", "final", "test"]) # ONE FINAL TEST
      

      但是,如果调用代码可能会提供列表而不喷出它,那么这种方法是不合适的。


      这种方法依赖于* 运算符的使用,这里有两种不同的使用方式。

      在函数定义上下文中 (*stringinput),这个运算符本质上使stringinput成为一个可变参数参数;也就是说,一个参数将传递给函数的所有参数“收集”到一个元组中,就runthis 而言,它就像一个列表(它可以被迭代)。如果我拨打电话runthis("foo", "bar", "baz")stringinput 的值将是("foo", "bar", "baz")

      您可以阅读有关可变参数here 的更多信息。

      在函数调用上下文中 (runthis(*["one", "final", "test"])),此运算符将“分解”或解包列表中的每个元素。本质上,runthis(*["one", "final", "test"]) 等价于runthis("one", "final", "test")

      您可以阅读更多关于喷溅的内容here

      【讨论】:

      • 嗨,谢谢。 “*”有什么作用?
      • "*" 是 splat 运算符。我将编辑我的帖子以包含有关它的更多信息。
      • @keynesiancross 我现在已经编辑了这些细节。
      猜你喜欢
      • 2013-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-10
      • 2010-10-29
      • 1970-01-01
      • 2014-04-12
      相关资源
      最近更新 更多