如何在每次调用next()时使用python返回多行?
你好,我是python的初学者,有一个简单的问题。 我被要求编写一个生成器来遍历一个txt文件,文件中的每一行是一个点的3个坐标(x,y,z) 如何在每次调用next()时返回5个点(5行) 这是我的代码,我每次只能生成一行 太多了如何在每次调用next()时使用python返回多行?,python,generator,Python,Generator,你好,我是python的初学者,有一个简单的问题。 我被要求编写一个生成器来遍历一个txt文件,文件中的每一行是一个点的3个坐标(x,y,z) 如何在每次调用next()时返回5个点(5行) 这是我的代码,我每次只能生成一行 太多了 import itertools def gen_points(name): f=open(name) for l in f: clean_string=l.rstrip() x,y,z=clean_
import itertools
def gen_points(name):
f=open(name)
for l in f:
clean_string=l.rstrip()
x,y,z=clean_string.split()
x= float(x)
y= float(y)
z= float(z)
yield x,y,z
f.close()
file_name=r"D:\master ppt\Spatial Analysis\data\22.txt"
a=gen_points(file_name)
g=itertools.cycle(a)
print(next(g))
只要等到你的三胞胎列表中有五个项目,你就会得到:
def gen_points(name):
with open(name) as f:
five_items = []
for l in f:
five_items.append(tuple(map(float,l.split())))
if len(five_items) == 5:
yield five_items
# create another empty object
five_items = []
if five_items:
yield five_items
另外,如果不是空的,则在循环结束时产生,以避免在元素数不能除以5时丢失最后的元素
旁白:clean\u string=l.rstrip()
是无用的,因为split
已经处理了换行和其他事情。您不必立即放弃,所以请保留输出,稍后再放弃:
## Adding batchsize so you can change it on the fly if you need to
def gen_points(name, batchsize = 5):
## The "with" statement is better practice
with open(name,'r') as f:
## A container to hold the output
output = list()
for l in f:
clean_string=l.rstrip()
x,y,z=clean_string.split()
x= float(x)
y= float(y)
z= float(z)
## Store instead of yielding
output.append([x,y,z])
## Check if we have enough lines
if len(output) >= batchsize:
yield output
## Clear list for next batch
output = list()
## In case you have an "odd" number of points (i.e.- 23 points in this situation)
if output: yield output