我有一个包含如下元组列表的文件:
(1, 4)
(569, 39)
(49, 69)
。 。 .
我有这个代码,但同时读取所有行,我只想读取行,例如第1行,并将值x,y设置在函数中,然后返回第2行并取值 x、y,然后再次执行,当我的文件长度完成时停止。
我可以在代码中更改什么来返回下一行?
import ast
def readfile():
filename = open('file.log')
result=[]
with open('file.log', 'r') as f:
lst = [ast.literal_eval(line) for line in f.readlines()]
for t in lst:
x, y = t
for t in [(x,y) for x in t[0:] for y in t[:1]]:
print x, y
value = (x, y)
result.append(value)
return result[1:-1]
print readfile()
最佳答案
my end goal is: take the values x, y, of the line 1 and use them in other function, when this function is done, return the line 2 and take other values for do it again, and stop when my lenght of my file is done.
听起来您想要一个从文件中迭代生成值的函数。示例实现:
import ast
def readfile():
with open('file.log', 'r') as f:
for line in f:
yield ast.literal_eval(line)
def do_something(a,b):
print "I am doing something with {} and {}".format(a,b)
for x,y in readfile():
do_something(x,y)
结果:
I am doing something with 1 and 4
I am doing something with 569 and 39
I am doing something with 49 and 69
关于python - 如何在这段Python代码中迭代元组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28593638/