你好我是python的初学者,有一个简单的问题。 我要求编写一个生成器来遍历一个txt文件,文件中的每一行都是一个点(x,y,z)的3个坐标 如何在每次调用next()时返回5个点(5行)?
这是我的代码,我每次只能生成一行 很多!
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))
答案 0 :(得分:5)
等到你的三元组列表中有五个项目,然后产生相反的结果:
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
如果不是空的话,在循环结束时也yield
,以避免在元素数量不能被5分割的情况下丢失最后的元素。
除此之外:clean_string=l.rstrip()
没用,因为split
已经处理过换行符等等。
答案 1 :(得分:1)
你不必立即屈服,所以保持输出然后再产生它:
## 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