保留字典的元素而不是流行元素?

时间:2019-06-19 13:47:16

标签: python-3.x list dictionary

function scaleDataURL(dataURL, maxWidth, maxHeight){
  return new Promise(done=>{
    var img = new Image;
    img.onload = ()=>{
      var scale, newWidth, newHeight, canvas, ctx, dx, dy;
      if(img.width < maxWidth){
        scale = maxWidth / img.width;
      }else{
        scale = maxHeight / img.height;
      }
      newWidth = img.width * scale;
      newHeight = img.height * scale;
      canvas = document.createElement('canvas');
      canvas.height = maxWidth;
      canvas.width = maxHeight;
      ctx = canvas.getContext('2d');
      dx = (maxWidth - newWidth) / 2;
      dy = (maxHeight - newHeight) / 2;
      console.log(dx, dy);
      ctx.drawImage(img, 0, 0, img.width, img.height, dx, dy, newWidth, newHeight);
      done(canvas.toDataURL());
    };
    img.src = dataURL;
  }); 
}

我如何仅保留l = {'apple': [0, 4], 'orange': [3], 'beer': [9], 'rice': [6], 'melon': [10, 11]}

我知道它们的长度是2。

3 个答案:

答案 0 :(得分:1)

您可以使用字典理解功能仅使用所需内容创建新的dict

l = {'apple': [0, 4], 'orange': [3], 'beer': [9], 'rice': [6], 'melon': [10, 11]}
result = {key: val for key, val in l.items() if len(val) == 2} # This will only keep entries with length 2.
print(result) # {'apple': [0, 4], 'melon': [10, 11]}

答案 1 :(得分:0)

过滤出字典值为if len(value) > 1的项目。

l = {'apple': [0, 4], 'orange': [3], 'beer': [9], 'rice': [6], 'melon': [10, 11]}

result = { key:value for key, value in l.items() if len(value) == 2}

print (result)

查看以下结果:

{'apple': [0, 4], 'melon': [10, 11]}

答案 2 :(得分:0)

您可以删除值的len不是2的键。

唯一的问题是,在循环浏览键时,字典无法更改大小,因此您可以通过首先复制键来解决此问题。

d = {'apple': [0, 4], 'orange': [3], 'beer': [9], 'rice': [6], 'melon': [10, 11]}
for k in list(d):  # Make copy of keys
    if len(d[k]) < 2:
        del d[k]
print(d)  # -> {'apple': [0, 4], 'melon': [10, 11]}

但是我建议对此进行字典理解。

相关问题