使用while循环完成列表信息转移/删除/信息录入和输出
1. 使用while循环将信息从一个列表转移至另外一个列表。(可适用于客户的转移场景)
eg. 再次火锅点单,先将想点的菜创建至一个列表;最终将这些菜清单转移至另外一个列表,并输出确认。
首先创建一个火锅点单列表和一个空列表:
hotpot_orders = ['sliced beef', 'pig brain', ' squid', 'shrimp paste', 'duck intestine']
finished_orders = [] 接着就可以用while循环和pop()语句将点单列表中的内容挨个删除直至为空,同时将删除内容挨个加入新的列表储存:
while hotpot_orders:list_order = hotpot_orders.pop()
#pop()会删除最后一个并储存print("I would like to have " + list_order + ".")finished_orders.append(list_order)
#通过append语句,则将一个个通过循环删除的内容添加进新列表中。while循环在hotpot_orders列表空后停止。 最后,则是一个新的语句(千万不能放进while语句循环,否则会添加一个,完整循环一次),将新列表打印出来即可,以便确认:
print("\nHere is your list! Please let me know if I missed anything!")
for finished_order in finished_orders:print(finished_order.title()) 输出结果:

- 如何将列表中已有的信息移除(包括此信息在列表中多次出现),并进行确认。
eg. 依旧火锅点单列表,其中包含一样菜式,重复几遍。需将其删除并确认。
首先,输入已有名单,并打印将删掉的信息
hotpot_orders = ['tofu puff', 'baby cabbage', 'sliced mutton', 'duck tongue', 'sliced mutton', 'prawn', 'sliced mutton']print("\n Sliced mutton have been sold out!") 然后,通过while循环删除所有‘sliced mutton’
#要注意while是否小写,while大写该语句无效
while 'sliced mutton' in hotpot_orders:hotpot_orders.remove('sliced mutton')
#del 删除需知道文字的具体位置,remove语句适合删除确定值 最后确认是否已经删掉:
print("\n Here is the latest menu with food we have now.")
print(hotpot_orders) 输出结果:

3.用while循环和用户输入创建键值对,并输出。
eg. 火锅蘸料的选择。每个人选择自己想要的火锅蘸料,选完后,输出确认。
首先,创建一个空字典和一个标志用以控制while循环
dipping_sauces = {}
customer_input = True 然后,用while循环将用户的输入信息导入字典,并在相应时间中指循环。
while customer_input:customer = input("\nWhat is your name?")response = input("What you would like for dipping sauce?")
#while 语句后不需跟 = True这样的语句,它本身就是默认为True才会执行dipping_sauces[customer] = response
#这里将用户的输入,对应的储存进字典repeat = input("\nAnyone else would like to order?")if repeat == 'no':customer_input = False 最后,通过已储存好的字典,输出信息
print("---------------Dipping Sauce List-----------------")
for customer, response in dipping_sauces.items():print(customer.title() + " would like to have " + response + " for dipping sauce.") 打印结果:
转载于:https://blog.51cto.com/13595859/2084046
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
