【问题标题】:Most pythonic way to check if an item is not a list then make it into a list? [duplicate]检查项目是否不是列表然后将其放入列表的大多数pythonic方法? [复制]
【发布时间】:2014-08-26 12:46:50
【问题描述】:

我正在编写一个可以接收标量 列表项的方法。我想要在该方法中做的第一件事是确保我正在使用列表。我想知道这样做的最pythonic方式。目前我正在做:

def print_item_or_list(list_or_item):
    if not isinstance(list_or_item, (list, tuple)):
        list_or_item = [list_or_item]

    # Now I can consistently work with an iterable
    for item in list_or_item:
         print item

还有更惯用的方式吗?

谢谢!

【问题讨论】:

  • 您可以使用iter() 函数,如果它不可迭代,则抛出TypeError
  • 通常的反对意见是字符串是可迭代的,所以调用iter() 并不能区分它们。确实没有“Pythonic”的方式来做到这一点,因为它是一个糟糕的 API。
  • @gipi - 列表也是可迭代的,这不是他要寻找的 IMO。
  • 为什么不只传递参数列表:def print_item_or_list(*arg)
  • @PadraicCunningham: isinstance("foo", collections.Iterable) == True

标签: python data-structures


【解决方案1】:

通常它在 Python 中完成的方式(或者我已经完成的方式)是使用简单地将变量用作列表,然后处理错误。这可以通过try...except 块来完成,如下所示:

def tryExceptExample(data):

    try:
        for a in data:    #or whatever code you want to run
            print a

    except TypeError:
        print "Invalid data"   #code you want to run if code in try block fails

    finally:
        print "fin"    #optional branch which always runs

样本输出:

>>> tryExceptExample([1,2,3])
1
2
3
fin
>>> tryExceptExample("abcd")
a
b
c
d
fin
>>> tryExceptExample(5)
Invalid data
fin

注意事项:

  • try 分支中的代码将一直运行,直到遇到错误,然后立即转到except,这意味着执行错误之前的所有行。为此,尽量将此分支中的行数保持在最低限度

  • 这里except 分支显示为TypeError。这意味着只有TypeErrors 将被此分支“捕获”,并且任何其他错误都将正常抛出。您可以根据需要拥有尽可能多的except 分支,以捕获尽可能多的错误。你也可以有一个“裸”的except 分支来捕获所有错误,但这被认为是糟糕的形式和非pythonic

【讨论】:

  • 对于列表,这将失败。
  • 如果你传递一个字符串作为输入,那么它会被打印len(astr) 次。这似乎是错误的。
  • 是的,应该是print a 而不是print data,已更正
【解决方案2】:

正如 Wooble 所说,您的函数首先不是惯用的。考虑:

def print_one_item(the_item):
    return print_many_items([the_item])

def print_many_items(the_items):
    for an_item in the_items:
        ...

【讨论】:

    【解决方案3】:

    你可以像type()一样使用

    if type(some_list) is not list:
        handle
    

    【讨论】:

    • 总的来说,我认为isinstance 是首选,因为它能够处理继承。
    猜你喜欢
    • 2015-01-10
    • 2012-03-01
    • 2011-04-14
    • 2017-02-25
    • 1970-01-01
    • 2010-11-30
    • 1970-01-01
    • 2015-03-20
    • 1970-01-01
    相关资源
    最近更新 更多