我需要为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
有更好的方法还是单行?
答案 0 :(得分:3)
with open(...) as fp: any(sync(line) for line in fp)
答案 1 :(得分:3)
好吧,几乎在一行(如果你允许我导入itertools module):
[ x for x in itertools.takewhile(
lambda line: sync(line) == 0, # <- predicate
open("file.txt")) ] # <- iterable
w / o文件示例:
>>> 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