python - 迭代月份列表时插入 None

标签 python python-2.7

我有一个包含年份/月份范围的列表。然后,我还有以下格式的用户计数: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/

相关文章:

python - xml 属性的顺序

python - 你怎么知道github存储库是用于python 2还是python 3

python-2.7 - 如何使用 python 中的 format() 方法在 E 指数后用零填充数字?

python - 根据空字符串切片 python 列表

python - 在python中没有负值的情况下进行插值

python - 如何使用索引从数据框中获取值?

python - 如何在 Windows 上安装 .egg Python 包(尝试使用 easy_install 不起作用)

python - 如何防止我的 Sprite 穿过 pygame 中的对象?

python - 为什么我的 Python 自定义数学重载类方法不起作用?

python-2.7 - 使用 Python Tweepy 搜索术语交集和并集