Python 迭代月份列表时插入无

Python 迭代月份列表时插入无,python,python-2.7,Python,Python 2.7,我有一个年/月范围的列表。然后,我还有一个使用这种格式的用户计数:total_users,month,year 基本上,我需要插入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') user

我有一个年/月范围的列表。然后,我还有一个使用这种格式的用户计数:total_users,month,year

基本上,我需要插入
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)]
我正在尝试这段代码,但问题是我会有比预期更多的Nones

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)
问题是,每次循环第二个for循环时,您都会创建一个新的列表元素,这意味着每个
每月
数据中有三个条目,而不是预期的一个条目。这里有一个解决方案:

data=()
i = 0
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,)
            break
    else:
        data = data + (None,)

一个不同的方法,但对我需要的有用

user_count_data=[]
for total, month, year in users_count:
    d={}
    d['month_year'] = str(int(year))+'/'+str(int(month))
    d['count'] = total
    user_count_data.append(d)

data=()
for each_month in all_months_necessary:              
    data = data + (next((item['count'] for item in user_count_data if item.get("month_year") and item["month_year"] == each_month), None), )

输出:
(2L,None,1L,None,None,None,None,None,None,None,1L)
最好将
用户数转换为字典。
还有另一条线:


再加上Jason的解释

你为什么要用元组来表示同构序列?@IgnacioVazquez Abrams你在说什么同构序列?一旦找到匹配项,thxI将
break
,并放弃
i
altogetherThank@robyschek。我添加了一个中断并修复了一个小错误。您将如何消除
i
?困难在于,实际上用户计数中的total、month、year的
实际上是通过三个单独的列表元素进行的,因此我需要一种方法来跟踪发生了多少次不匹配。我想听听你的建议。谢谢。别忘了,
for
语句后面可能会跟一个block,当不发生中断时执行该block。追加
None
there@robyschek非常感谢你的建议。我做了更改,它工作了,所以上面的代码被编辑了。你的两行dict解决方案很好。再次感谢。杰森,是的,这正是我的意思。
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]