我正在尝试根据if条件将列表追加到字典中。我为此问题编写了一个工作函数,但我想在列表理解中编写该程序。
以下功能按月组织所有曲目。结果将是一个以月为键,音轨为值的字典。
[[j for j in lst2] for i in month if j[-2] == i]
#I tried this list comprehension code for my function given below
列名
[位置,曲目名称,艺术家,流,Datetime.object,地区,月份,日期]
Input : #my working code
[['1','Starboy','The Weeknd','3135625',datetime.datetime(2017, 1, 1, 0, 0),
'global',1,1],
['2','Closer','The Chainsmokers','3015525',datetime.datetime(2017, 1, 1, 0, 0),
'global',1,1]
['3','Party Monster','The Weeknd','829599',datetime.datetime(2017, 2, 2, 0, 0),
' global',2,2]]
def organized(lst2):
month = [1,2]
edict = {}
for i in month:
elst = []
for j in lst2:
if j[-2] == i:
elst.append(j)
edict[i] = elst
return edict
output
{1: [['1', 'Starboy', 'The Weeknd', '3135625',
datetime.datetime(2017, 1, 1, 0, 0),'global', 1, 1],
['2', 'Closer', 'The Chainsmokers', '3015525',
datetime.datetime(2017, 1, 1, 0, 0), 'global', 1, 1]]
2:[[‘3’, 'Party Monster', 'The Weeknd', '829599',
datetime.datetime(2017, 2, 2, 0, 0), 'global', 2, 2]]}
答案 0 :(得分:3)
您的输出是dict
,因此您需要一个dict
理解(嵌套了list
理解):
def organized(lst2):
month = [1, 2]
return {i: [j for j in lst2 if j[-2] == i] for i in month}