Python idiom to return first item or None

后端 未结 24 2062
清酒与你
清酒与你 2020-12-07 07:46

I\'m sure there\'s a simpler way of doing this that\'s just not occurring to me.

I\'m calling a bunch of methods that return a list. The list may be empty. If the

24条回答
  •  不知归路
    2020-12-07 08:04

    def head(iterable):
        try:
            return iter(iterable).next()
        except StopIteration:
            return None
    
    print head(xrange(42, 1000)  # 42
    print head([])               # None
    

    BTW: I'd rework your general program flow into something like this:

    lists = [
        ["first", "list"],
        ["second", "list"],
        ["third", "list"]
    ]
    
    def do_something(element):
        if not element:
            return
        else:
            # do something
            pass
    
    for li in lists:
        do_something(head(li))
    

    (Avoiding repetition whenever possible)

提交回复
热议问题