考虑使用这种类型的列表:
month_list = ['Mar', 'Aug', 'Okt', 'Nov']
value_for_each_month = [4, 10, 8, 5]
因此,每个值都属于month_list中的月份,例如'Mar' - > 4,'Aug' - > 10等等..
现在,如何在Python中填充两个列表以实现此结果:
month_list_new = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
value_for_each_month_new = [0, 0, 4, 0, 0, 0, 0, 10, 0, 8, 5, 0]
答案 0 :(得分:2)
创建将月份名称映射到值的字典...
>>> month_list = ['Mar', 'Aug', 'Okt', 'Nov']
>>> value_for_each_month = [4, 10, 8, 5]
>>> month_values = dict(zip(month_list, value_for_each_month))
>>> month_values
{'Aug': 10, 'Mar': 4, 'Nov': 5, 'Okt': 8}
...而不是在列表理解中使用该词典:
>>> month_list_new = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
>>> value_for_each_month_new = [month_values.get(m, 0) for m in month_list_new]
>>> value_for_each_month_new
[0, 0, 4, 0, 0, 0, 0, 10, 0, 0, 5, 0]