大多数pythonic方式检查项目是否不是列表然后将其列入列表?

时间:2014-08-26 12:46:51

标签: python data-structures

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

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

是否有更惯用的方式?

谢谢!

3 个答案:

答案 0 :(得分:2)

通常它在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

答案 1 :(得分:1)

正如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:
        ...

答案 2 :(得分:0)

你可以{/ 1}}在

中运作
type()