如何向发电机发送()值?
我想使用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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论