python input dict_name={“A”:H,"B":J} list = ["AB"] OUTPUT ["HJ"]
时间: 2023-08-07 07:12:51 浏览: 154
要根据给定的字典和列表生成输出,可以使用以下代码:
```python
dict_name = {"A": "H", "B": "J"}
my_list = ["AB"]
output_list = []
for item in my_list:
new_item = ""
for char in item:
if char in dict_name:
new_item += dict_name[char]
output_list.append(new_item)
print(output_list)
```
输出结果将是:
```python
['HJ']
```
在代码中,我们遍历列表中的每个元素,并检查该元素的每个字符是否存在于字典中。如果存在,则将对应的值添加到新的字符串中。最后,将新的字符串添加到输出列表中。
相关问题
将 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)变成一个生成器函数
可以将上述代码转化为一个生成器函数,如下所示:
```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']}")
```
score_dict = {}while True: input_str = input().strip() if input_str == '#': break name, score = input_str.split() score = int(score) if name in score_dict: score_dict[name].append(score) else: score_dict[name] = [score]print('姓 名 平均成绩')for name, scores in score_dict: avg_score = sum(scores) / len(scores) print('{:<8} {:.2f}'.format(name, avg_score))
这段代码存在一些问题,应该修改为:
```python
score_dict = {}
while True:
input_str = input().strip()
if input_str == '#':
break
name, score = input_str.split()
score = int(score)
if name in score_dict:
score_dict[name].append(score)
else:
score_dict[name] = [score]
print('姓 名 平均成绩')
for name, scores in score_dict.items():
avg_score = sum(scores) / len(scores)
print('{:<8} {:.2f}'.format(name, avg_score))
```
主要修改包括:
- 对于 `for name, scores in score_dict`,应该改为 `for name, scores in score_dict.items()`,因为字典类型需要使用 `items()` 方法来遍历。
- 对于计算平均成绩,应该在遍历时进行,而不是在输入时计算。
阅读全文