在嵌套列表Python中求和特定值

时间:2019-06-26 23:27:29

标签: python

我有一个看起来像这样的嵌套列表:

 z = np.polyfit(x, y1, 6)  
 p = np.poly1d(z) 

 xp = np.linspace(0, 1, 100)
 line = plt.plot(x, y1, '.', xp, p(xp), '-', label=' G_MEAN_1 ')
 plt.ylim(0, 1)
 plt.legend()
 plt.show()

我想对列表中每个字母值的嵌套列表中的值求和,以便输出如下所示:

function searchFolders() {
  var sheet1 = SpreadsheetApp.getActive().getSheetByName('Search Folder');
  var range = [];
  range.push([ "FolderId", "Folder Name", "Owner", "Date Created", "URL" ]);

  var parentId = sheet1.getRange(2,1,sheet1.getLastRow(),sheet1.getLastColumn()).getValues(); // list of parent folderids

  for (i=0; i<parentId.length; i++) {
    var parfolder = DriveApp.getFolderById(parentId[i][0]).getFolders();  //retrieves the folders
    while(parfolder.hasNext()){
      var pchild = parfolder.next();

      var row = [];
      row.push(pchild.getId(),
               pchild.getName(),
               pchild.getOwner().getEmail(),
               pchild.getDateCreated(),
               pchild.getUrl())
      range.push(row);

      sheet1.getRange(i+2,2,range.length,range[0].length).setValues(range);
    }
  }
}

我尝试使用for循环,但是找不到解决方法。

1 个答案:

答案 0 :(得分:0)

使用reduce和list comp可能有一个衬里,但是我看不到它。

nested = [['a', 1], ['v', 2], ['a', 5], ['v', 3]]

from collections import defaultdict
d = defaultdict(int)
for i in nested:
    d[i[0]] += i[1]

retval = []    
for k, v in d.items():
    retval.append([k, v])

print(retval)  # [['a', 6], ['v', 5]]