如何向发电机发送()值?

发布于 2025-01-24 15:34:14 字数 924 浏览 3 评论 0原文

我想使用send()方法将另一个来宾添加到发电机上,该方法在guest_list.txt上迭代。我知道我需要使用send()方法,但是我只是不了解 n =屈服值逻辑。

下面的代码从Guest_list.txt输出前10位来宾。我想将“简,35”添加到被返回的客人,作为第11位客人。

和;

guestlist_generator.send(“ jane,35”)

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_generator = read_guestlist("guest_list.txt")
for i in range(10): 
    print(next(guestlist_generator))

guest_list.txt;

Tim,22
Tonya,45
Mary,12
Ann,32
Beth,20
Sam,5
Manny,76
Kenton,15
Kenny,27
Dixie,46
Mallory,32
Julian,4
Edward,71
Rose,65

I want to add another guest to a generator, using send() method, that iterates over the guest_list.txt. I know I need to use the send() method, but I just can't understand the n = yield value logic.

The code below outputs the first 10 guests from the guest_list.txt. I want to add "Jane,35" to the guests that are being returned, as an 11th guest.

With;

guestlist_generator.send("Jane,35")

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_generator = read_guestlist("guest_list.txt")
for i in range(10): 
    print(next(guestlist_generator))

guest_list.txt;

Tim,22
Tonya,45
Mary,12
Ann,32
Beth,20
Sam,5
Manny,76
Kenton,15
Kenny,27
Dixie,46
Mallory,32
Julian,4
Edward,71
Rose,65

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文