鱼C论坛

 找回密码
 立即注册
查看: 1677|回复: 2

[已解决]多行输入并存入字典中<新人求助>

[复制链接]
发表于 2021-5-16 20:17:19 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
题目要求:

请从标准输入录入多个国家的名字和对应的GDP,存入GDP字典中。(字典不为空)

【样例输入】

USA 95

China 80

Japan 50

ok

【样例说明】

输入为多行,分别是以空格分隔开的国家和对应的GDP值,以"ok"结束

GDP = {

'USA': 95,

'China': 80,

'Japan': 50

}
最佳答案
2021-5-16 20:48:52

while 循环 if 判断输入是否为 ok 以及题目要求字典不为空, 即可实现:

参考代码:

  1. GDP = {}
  2. while True:
  3.     user_input = input()
  4.     if user_input == 'ok':
  5.         if not GDP:
  6.             print('GDP字典不能为空')
  7.             continue
  8.         break
  9.     nation,gdp = user_input.split()
  10.     GDP[nation] = int(gdp)
  11. print(GDP)
复制代码


若没有要求字典不为空则可以直接将是否输入 ok 来当作 while 循环条件

参考代码:

  1. user_input = input()
  2. GDP = {}
  3. while user_input != 'ok':
  4.     nation,gdp = user_input.split()
  5.     GDP[nation] = int(gdp)
  6.     user_input = input()
  7. print(GDP)
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2021-5-16 20:48:52 | 显示全部楼层    本楼为最佳答案   

while 循环 if 判断输入是否为 ok 以及题目要求字典不为空, 即可实现:

参考代码:

  1. GDP = {}
  2. while True:
  3.     user_input = input()
  4.     if user_input == 'ok':
  5.         if not GDP:
  6.             print('GDP字典不能为空')
  7.             continue
  8.         break
  9.     nation,gdp = user_input.split()
  10.     GDP[nation] = int(gdp)
  11. print(GDP)
复制代码


若没有要求字典不为空则可以直接将是否输入 ok 来当作 while 循环条件

参考代码:

  1. user_input = input()
  2. GDP = {}
  3. while user_input != 'ok':
  4.     nation,gdp = user_input.split()
  5.     GDP[nation] = int(gdp)
  6.     user_input = input()
  7. print(GDP)
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2021-5-16 20:54:16 | 显示全部楼层
本帖最后由 qq1151985918 于 2021-5-16 20:58 编辑
  1. GDP = { }
  2. while True:
  3.     print(len(GDP) + 1, end = ".")
  4.     inData = input("请输入国家和对应的GDP以空格分隔(输入“ok”退出):")
  5.     if inData == "ok":
  6.         break
  7.     if len(inData.split()) != 2:
  8.         print("----输入错误请重新输入",end = "\n----")
  9.         continue
  10.     else:
  11.         GDP[inData.split()[0]] = inData.split()[-1]
  12. print(GDP)   
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-4-20 07:17

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表