4 回答
TA贡献1946条经验 获得超3个赞
编辑:
我相信更快的解决方案是使用dict comprehensionwith itertools.product。解决方案只是一行代码:
import itertools
example_dict = {x:[] for x in [x[0]+x[1] for x in itertools.product(info,years)]}
输出与以下解决方案相同。
正如 han solo 在他们的评论中所建议的那样,这似乎更合适defaultdict(list)。基本上解决方案是:
from collections import defaultdict
example_dict = defaultdict(list)
for i in years:
for j in info:
example_dict[j+i]
print(example_dict)
输出:
defaultdict(list,
{'championship_won2013': [],
'championship_won2014': [],
'championship_won2015': [],
...
'semi-finals2018': [],
'semi-finals2019': [],
'semi-finals2020': []})
TA贡献1828条经验 获得超3个赞
您可以使用一维字典并在一个字符串中合并 itme 和不好的年份,您宁愿使用二维字典并首先填充空列表,然后通过两个信息访问:项目+日期
一个项目然后一年
values = {i: {year: [] for year in years} for i in info}
{'played_games': {'2020': [], '2019': [], '2018': [], '2017': [], '2016': [], '2015': [], '2014': [], '2013': []},
'games_won': {'2020': [], '2019': [], '2018': [], '2017': [], '2016': [], '2015': [], '2014': [], '2013': []},
'efectivity': {'2020': [], '2019': [], '2018': [], '2017': [], '2016': [], '2015': [], '2014': [], '2013': []},
...}
# add data like
values["played_games"]['2014'].append("foo")
一年然后一个项目
values = {year: {i: [] for i in info} for year in years}
{'2020': {'played_games': [], 'games_won': [], 'efectivity': [], 'championship_won': [], 'finals': [], 'semi-finals': [], 'quarterfinals': []},
'2019': {'played_games': [], 'games_won': [], 'efectivity': [], 'championship_won': [], 'finals': [], 'semi-finals': [], 'quarterfinals': []},
'2018': {'played_games': [], 'games_won': [], 'efectivity': [], 'championship_won': [], 'finals': [], 'semi-finals': [], 'quarterfinals': []},
...}
# add data like
values['2014']["played_games"].append("foo")
TA贡献1808条经验 获得超4个赞
您可以创建一个包含 n 个空列表的列表。与n = len(info) * len(years)
。其中 pos 0 的列表是 (info[0],years[0]) ,1 的列表是 (info[0],years[1])....
如果需要,您还可以将名称存储在字符串列表中,具有相同的原理(信息和年份的双循环)。
TA贡献1966条经验 获得超4个赞
使用 2 个循环,你可以试试这个:
years = ["2020", "2019", "2018", "2017", "2016", "2015", "2014", "2013"]
info = ["played_games", "games_won", "efectivity", "championship_won", "finals", "semi-finals", "quarterfinals"]
all_arrays_dict = {}
for x in years:
for y in info:
all_arrays_dict[y+x] = []
print(all_arrays_dict)
这是输出字典:
{
"played_games2020": [],
"games_won2020": [],
"efectivity2020": [],
"championship_won2020": [],
"finals2020": [],
"semi-finals2020": [],
"quarterfinals2020": [],
"played_games2019": [],
"games_won2019": [],
.
.
.
}
添加回答
举报