gpt4 book ai didi

python - 尝试将数组与用户输入匹配时出错

转载 作者:太空宇宙 更新时间:2023-11-04 04:40:54 24 4
gpt4 key购买 nike

谁能指出我做错了什么。我正在尝试将用户输入与数组相匹配,但似乎没有得到任何响应。任何帮助都很棒。谢谢。

`#import json module to read json file
import json

#open then read file and close file
fin=open("weather-data.json","r")
json_string=fin.read()
fin.close()

#Json to python dictionary
array=json.loads(json_string)

#User input
desired_month=input("Input a month number 1 -5:")
desired_day=input("Pick a day in the month:")

#matching day and month to dic.
for d in array:
if desired_month==d["month"] and desired_day==d["day"]:
print (d[{"high"}],d[{"low"}])

`

weather-data.json 格式如下:

[
{
"year": 2014,
"month": 1,
"day": 1,
"high": 22,
"low": 16,
"precip": 0.25
},
{
"year": 2014,
"month": 1,
"day": 2,
"high": 21,
"low": 10,
"precip": 0.22
}, ...
]

最佳答案

主要问题是您将 desired_monthdesired_day 存储为字符串,而 JSON 文件将它们存储为整数。因此,您在所需值与存储在 JSON 中的值之间的比较总是会评估为 False,并且永远不会打印高温和低温。

第二个问题是在打印高温和低温时存在 Python 语法错字。在给定键的情况下访问字典值的语法是 d["high"],而不是 d[{"high"}]

这里是修改后的版本(weather.py):

import json

# Load JSON
with open("weather-data.json") as weather_data_file:
weather_list = json.load(weather_data_file)

# Get user inputs (as strings) and convert them integers for later comparison
desired_month = int(input("Input a month number 1 -5:"))
desired_day = int(input("Pick a day in the month:"))

# matching day and month to content of JSON file
for weather_entry in weather_list:
if desired_month == weather_entry["month"] and desired_day == weather_entry["day"]:
print(weather_entry["high"], weather_entry["low"])

程序的示例输出:

➜ python weather.py
Input a month number 1 -5:2
Pick a day in the month:25
22 6

关于python - 尝试将数组与用户输入匹配时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50663145/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com