python - 如何在这段Python代码中迭代元组?

标签 python

我有一个包含如下元组列表的文件:

(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/

相关文章:

python - 了解 hyperopt TPE 算法

python - 从生成器克隆 Babeltrace 事件以进行随机访问遍历

python - python中二维和一维数组的元素明智乘法

python - 如何将 utf-8 字节数组解码为 Python2 中的字符串?

python - 将 Python 扩展 (.pyd) 动态链接到另一个扩展

python - 导入错误 : cannot import name 'input_reader_pb2'

javascript - 在 django 应用程序中打包 javascript 和 css 文件以供重用,通过 pip 安装?

Python 列表理解

python - 'utf- 8' codec can' t 解码位置 11 中的字节 0x92 : invalid start byte

python - 您如何处理 REST API 服务器中的高吞吐量函数?