python - Python:根据多个字典中的值生成新名称
问题描述
对 python 来说相对较新,如果问题/脚本冗长且含糊不清,我们深表歉意。下面的脚本返回搜索到的球队名称的键和值(例如:2,夏洛特黄蜂队);但是,我也希望它返回它所在的联赛名称。如'nfl'、'nba'、'mlb';根据它所在的字典(例如:2,夏洛特黄蜂队,nba)。已经为此工作了一段时间,但找不到动态解决方案。我在这里先向您的帮助表示感谢!
NFL_Teams = {1: "Arizona Cardinals", 2: "Atlanta Falcons", 3: "Baltimore Ravens"}
NBA_Teams = {1:'Washington Wizards', 2:'Charlotte Hornets', 3: 'Atlanta Hawks'}
MLB_Teams = {1: 'Los Angeles Dogers', 2: 'Cincinnati Reds', 3: 'Toronto Blue Jays'}
def Standings(reply):
def dictionary_search(name, dictionary):
for key, value in dictionary.items():
if value == name:
return True # Boolean to show if team name is in merged dictionaries.
if key == name:
pass # Used as a throw-away variable
for single_dictionary in (NFL_Teams, NBA_Teams, MLB_Teams):
if dictionary_search(reply, single_dictionary):
for key, value in single_dictionary.items():
if reply == value:
print(key, value)
break
else:
print('Please Try Again')
Standings('Charlotte Hornets')
解决方案
用作键的数字重要吗?反过来将它们读入字典是否有意义?- 然后你可以使用一个try except KeyError
语句。这对于非常大的字典可能更可取(尽管对于联盟中的球队来说情况并非如此)。这也可能是一种更面向对象的思维方式:球队名称是对象标识符,而(我假设数字是当前联赛排名?)联赛排名是一个属性(并且是一个可变属性)。例如(改编 Aaron_ab 的回答)
teams = {'NFL': {"Arizona Cardinals":1, "Atlanta Falcons":2, "Baltimore Ravens":3},
'NBA': {'Washington Wizards':1, 'Charlotte Hornets':2, 'Atlanta Hawks':3},
'MLB': {'Los Angeles Dogers':1, 'Cincinnati Reds':2, 'Toronto Blue Jays':3}}
def standings(team):
for league, teams_dict in teams.items():
try:
teams_dict[team]
print(teams_dict[team], team)
print(league)
break
except KeyError:
continue
或者,删除数字并拥有一个列表字典(其中列表的顺序是当前的联赛顺序):
import numpy as np
teams = {'NFL': ["Arizona Cardinals", "Atlanta Falcons", "Baltimore Ravens"],
'NBA': ['Washington Wizards', 'Charlotte Hornets', 'Atlanta Hawks'],
'MLB': ['Los Angeles Dogers', 'Cincinnati Reds', 'Toronto Blue Jays']}
def standings(team):
for league, teams_list in teams.items():
if team in teams_list:
print(team, np.where(np.array(teams_list)==team)[0])
print(league)
推荐阅读
- javascript - React-redux 在 TypeError 中渲染帖子时出现错误:无法读取未定义的属性“地图”但控制台包含所有帖子
- r - R ggplotly 使用 geom_sf() 和离散填充比例显示错误的工具提示
- php - 在 Wordpress 中显示特定产品的库存
- .net - 如何还原 KB4533097 引入的 SameSite cookie 更改
- javascript - 自动调整文本区域的大小以在加载时显示所有文本,而无需在 Blazor 中滚动
- reporting-services - SSRS 将日期时间参数设置为今天,但可用值是任何日期
- visual-studio - 多个 VLAN 上的团队是否连接到单个 Team Foundation Server?
- c++ - If I write a string literal in a block, will the entire string data be copied from data section?
- c++ - 寻求帮助以找到我无法解决的堆栈溢出错误的来源
- php - Symfony 4 用关系更新理论实体