代码之家  ›  专栏  ›  技术社区  ›  Sai Kumar

比较列表中的值以创建字典?

  •  0
  • Sai Kumar  · 技术社区  · 8 年前

    我正试图根据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]]}
    
    1 回复  |  直到 8 年前
        1
  •  3
  •   user2390182    8 年前

    你的输出是 dict ,所以您需要 双关语 理解 list 嵌套在其中的理解):

    def organized(lst2):
        month = [1, 2]
        return {i: [j for j in lst2 if j[-2] == i] for i in month}