使用另一个列表的元素创建空列表

我有一份年份清单:


years = ["2020", "2019", "2018", "2017", "2016", "2015", "2014", "2013"]

以及我想从网络抓取中获取的信息列表:


info = ["played_games", "games_won", "efectivity", "championship_won", "finals", "semi-finals", "quarterfinals"]

我需要迭代多年,这样我就可以用信息中元素的名称+相应的年份来制作空列表,这样我就可以稍后附加信息,即:


played_games2020 = []

games_won2020 = []

efectivity2020 = []

etc

played_games2019 = []

games_won2019 = []

efectivity2019 = []

etc

任何帮助将非常感激!问候


阿晨1998
浏览 207回答 4
4回答

智慧大石

编辑:我相信更快的解决方案是使用dict comprehensionwith itertools.product。解决方案只是一行代码:import itertoolsexample_dict = {x:[] for x in [x[0]+x[1] for x in itertools.product(info,years)]}输出与以下解决方案相同。正如 han solo 在他们的评论中所建议的那样,这似乎更合适defaultdict(list)。基本上解决方案是:from collections import defaultdictexample_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': []})

子衿沉夜

您可以使用一维字典并在一个字符串中合并 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 likevalues["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 likevalues['2014']["played_games"].append("foo")

炎炎设计

您可以创建一个包含 n 个空列表的列表。与n = len(info) * len(years)。其中 pos 0 的列表是 (info[0],years[0]) ,1 的列表是 (info[0],years[1])....如果需要,您还可以将名称存储在字符串列表中,具有相同的原理(信息和年份的双循环)。

慕标5832272

使用 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": [],  .  .  .}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python