我有一个包含年份/月份范围的列表。然后,我还有以下格式的用户计数:total_users、month、year。
基本上,当 all_months_necessary 中没有该月的计数值时,我需要插入 None
。
all_months_necessary=('2015/1', '2015/2', '2015/3', '2015/4', '2015/5', '2015/6', '2015/7', '2015/8', '2015/9', '2015/10', '2015/11', '2015/12', '2016/1')
users_count=[(2L, 1.0, 2015.0), (1L, 3.0, 2015.0), (1L, 1.0, 2016.0)]
我正在尝试这段代码,但问题是我将得到比预期更多的 None。
data=()
for each_month in all_months_necessary:
for total, month, year in users_count:
if each_month == str(int(year))+'/'+str(int(month)):
data = data + (total,)
else:
data = data + (None,)
预期:data=(2L, None, 1L, None, None, ..., 1L)
最佳答案
将users_count
转换为字典可能会更好。
还有一个onetwoliner:
user_count_dict = {str(int(year))+'/'+str(int(month)): total for total, month, year in users_count}
# get(x) returns None if a key not in the dict
data = [user_count_dict.get(x) for x in all_months_necessary]
并请 Jason 进行解释
关于python - 迭代月份列表时插入 None,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37040171/