如何使用发送方法给这个生成器添加名字和年龄

问题描述 投票:0回答:0

我目前正在学习 python 课程,但我在这一步上遇到了困难。我该如何解决这个问题?

这是我到目前为止完成的代码以及任务的屏幕截图和我坚持的步骤。此外,我们还使用了一个 txt 文件,该文件截屏并放入我们用作生成器实例化中的参数“guest_list.txt”。这一步的目标是使用生成器中的 .send() 方法将姓名和年龄添加到生成器并生成姓名并将信息添加到客人字典the step ive completed the step im stuck on the txt file we put as the argument

guests = {}


def read_guestlist(file_name):
  text_file = open(file_name,'r')
  while True:
    line_data = text_file.readline().strip().split(",")
    if len(line_data) < 2:
    # If no more lines, close file
      text_file.close()
      break
    name = line_data[0]
    age = int(line_data[1])
    guests[name] = age
    yield name
    

guestlist_gen = read_guestlist("guest_list.txt")

maxi = 9
count = 0

for one in guestlist_gen:
  print(one)
  if count == maxi:
    guestlist_gen.close()
  else:
    count += 1

python-3.x generator
© www.soinside.com 2019 - 2024. All rights reserved.