将 for index, adcode_dict in enumerate(adcode_list, 1): adcode = adcode_dict["adcode"] full_url = base_url + adcode response = requests.get(full_url) json_data = response.json() try: weather_name = json_data.get("data").get("data")[0].get("live").get("weather_name") adcode_dict["weather_name"] = weather_name if weather_name == '晴': sunny += 1 elif weather_name == '多云': cloud += 1 elif weather_name == '阴': being_cloud += 1 elif '雨' in weather_name: rain += 1 else: haze += 1 print(index, adcode_dict) except Exception as e: print(e)变成一个生成器函数
时间: 2024-04-21 17:29:10 浏览: 107
adcode拼音版_adcode99_中国县级城市_中文+拼音_静宁县adcode_
可以将上述代码转化为一个生成器函数,如下所示:
```python
import requests
def get_weather_info(adcode_list):
base_url = "http://xxx.xxx.xxx.xxx/weather/"
sunny = 0
cloud = 0
being_cloud = 0
rain = 0
haze = 0
for index, adcode_dict in enumerate(adcode_list, 1):
adcode = adcode_dict["adcode"]
full_url = base_url + adcode
response = requests.get(full_url)
json_data = response.json()
try:
weather_name = json_data.get("data").get("data")[0].get("live").get("weather_name")
adcode_dict["weather_name"] = weather_name
if weather_name == '晴':
sunny += 1
elif weather_name == '多云':
cloud += 1
elif weather_name == '阴':
being_cloud += 1
elif '雨' in weather_name:
rain += 1
else:
haze += 1
yield index, adcode_dict
except Exception as e:
print(e)
```
这个生成器函数会依次返回每个地区的天气信息,并且会统计出晴、多云、阴、雨、霾的数量。你可以使用`next()`或者`for`循环来获取每个地区的天气信息。例如:
```python
adcode_list = [...] # 假设这里是一些地区的adcode列表
gen = get_weather_info(adcode_list)
for index, adcode_dict in gen:
print(f"地区{index}的天气信息:{adcode_dict['weather_name']}")
```
阅读全文