-6

我需要继续调用sync每一行,file.txt直到函数返回非零(即它失败时)。目前我计划做以下事情。

for line in file("file.txt"):
        change=int(line)
        cp_success=sync(change) #check the return value of function sync
        if cp_success!=0 : 
            break               #Try using a break statement

有没有更好的方法或单线?

4

2 回答 2

3

好吧,几乎在一行中(如果您允许我导入itertools 模块):

[ x for x in itertools.takewhile(
    lambda line: sync(line) == 0,    # <- predicate
    open("file.txt")) ]              # <- iterable

不带文件的示例:

>>> import itertools
>>> def sync(n):
...   if n == 3: return -1 # error
...   return 0

>>> lines = [1, 2, 3, 4, 5, 6]
>>> [ x for x in itertools.takewhile(lambda x: sync(x) == 0, lines) ]
[1, 2]

但是你真的不应该掩盖事情,所以为什么不只是:

with open("file") as fh:
    for line in fh:
        if not sync(int(line)) == 0:
            break
于 2013-01-01T03:42:32.283 回答
3
with open(...) as fp: any(sync(line) for line in fp)
于 2013-01-01T03:40:03.983 回答