删除和替换Python中列表列表中的值

时间:2016-06-06 15:12:29

标签: python python-3.x

我的列表如下:

[[{
        'canBeAdded' : True,
        'categories' : ['Diving', 'Sports'],
        'relevanceRank' : 1,
        'rankSource' : 'NONE',
        'value' : 1.0,
        'canBeRemoved' : True,
        'displayStartDate' : '2013-02-10T05:00:00Z',
        'filterTags' : [],
        'relevanceScore' : -1.0,
    }
], [{
        'canBeAdded' : True,
        'categories' : ['Bucket', 'Sports'],
        'relevanceRank' : 1,
        'rankSource' : 'NONE',
        'value' : 1.0,
        'canBeRemoved' : True,
        'displayStartDate' : '2013-02-10T05:00:00Z',
        'filterTags' : [],
        'relevanceScore' : -1.0,
    }
]]

我想执行以下操作:

  • 删除' rankSource' :' NONE'列表中的元素
  • 更新' canBeAddedToCard'元素为假
  • update' relevRank'和" relatedScore'元素为0

1 个答案:

答案 0 :(得分:0)

开始阅读: https://people.duke.edu/~ccc14/sta-663/IntroductionToPythonSolutions.html

试试这个:

LL =  [[{
        'canBeAdded' : True,
        'categories' : ['Diving', 'Sports'],
        'relevanceRank' : 1,
        'rankSource' : 'NONE',
        'value' : 1.0,
        'canBeRemoved' : True,
        'displayStartDate' : '2013-02-10T05:00:00Z',
        'filterTags' : [],
        'relevanceScore' : -1.0,
    }
], [{
        'canBeAdded' : True,
        'categories' : ['Bucket', 'Sports'],
        'relevanceRank' : 1,
        'rankSource' : 'NONE',
        'value' : 1.0,
        'canBeRemoved' : True,
        'displayStartDate' : '2013-02-10T05:00:00Z',
        'filterTags' : [],
        'relevanceScore' : -1.0,
    }
]]

for i, row in enumerate(LL):
    LL[i][0]['relevanceRank']    = 0
    LL[i][0]['relevanceScore']   = 0
    LL[i][0]['canBeAddedToCard'] = False
    del LL[i][0]['rankSource']      

 #   [[{'canBeAdded': True,
 #      'canBeAddedToCard': False,
 #      'canBeRemoved': True,
 #      'categories': ['Diving', 'Sports'],
 #      'displayStartDate': '2013-02-10T05:00:00Z',
 #      'filterTags': [],
 #      'relevanceRank': 0,
 #      'relevanceScore': 0,
 #      'value': 1.0}],
 #    [{'canBeAdded': True,
 #      'canBeAddedToCard': False,
 #      'canBeRemoved': True,
 #      'categories': ['Bucket', 'Sports'],
 #      'displayStartDate': '2013-02-10T05:00:00Z',
 #      'filterTags': [],
 #      'relevanceRank': 0,
 #      'relevanceScore': 0,
 #      'value': 1.0}]]