私信  •  关注

Peter Wood

Peter Wood 最近创建的主题
Peter Wood 最近回复了

您可以将它们全部放入一个函数中,并生成结果:

def gen():
    yield expensive_call("a")
    yield expensive_call_2("b", "c")
    yield expensive_call("d")


result = next(
    (value for value in gen() if value is not None),
    'All are Nones')

另一个解决方案是 partial 应用程序:

from functools import partial

calls = [partial(expensive_call, 'a'),
         partial(expensive_call_2, 'b', 'c'),
         partial(expensive_call, 'd')]

然后评估:

next((result for call in calls
      for result in [call()]
      if result is not None),
     'All results None')
6 年前
回复了 Peter Wood 创建的主题 » 用python从文本文件中提取数据

你可以使用 itertools.groupby :

from itertools import groupby

with open(filename) a f:
    categs = [list(group) for (key, group) in groupby(f.splitlines(), key='CATEG:')]