Python 如何删除列表中的前16条记录?

Python 如何删除列表中的前16条记录?,python,list,Python,List,我只想得到16条记录,如果超过16条,那么从列表中删除前16条 我的代码: ItemList = { "items": [ [ [19,1],[19,2],[19,3],[19,4],[19,5],[19,6],[19,7],[19,8],[19,9],[19,10],[19,11],[19,12],[19,13],[19,14],[19,15],[19,16],[19,17],[19,18],[19,19],[19,20],[19,21],[19

我只想得到16条记录,如果超过16条,那么从列表中删除前16条

我的代码:

ItemList = {
    "items": [
        [
            [19,1],[19,2],[19,3],[19,4],[19,5],[19,6],[19,7],[19,8],[19,9],[19,10],[19,11],[19,12],[19,13],[19,14],[19,15],[19,16],[19,17],[19,18],[19,19],[19,20],[19,21],[19,22],[19,23],[19,24],[19,25],[19,26],[19,27],[19,28],[19,29],[19,30],[19,31],[19,32], 
        ],
        [],
        [],
    ],
}

if len(ItemList["items"][0]) > 16:
    for index in xrange(16):
        ItemList["items"][0].remove(ItemList["items"][0][index])
print ItemList["items"][0]
但它不起作用

这是我的输出:

[[19, 2], [19, 4], [19, 6], [19, 8], [19, 10], [19, 12], [19, 14], [19, 16], [19, 18], [19, 20], [19, 22], [19, 24], [19, 26], [19, 28], [19, 30], [19, 32]]
我只想得到这个:

[[19,17],[19,18],[19,19],[19,20],[19,21],[19,22],[19,23],[19,24],[19,25],[19,26],[19,27],[19,28],[19,29],[19,30],[19,31],[19,32]]

您可以使用切片:

>>> ItemList['items'][0][16::]
[[19, 17], [19, 18], [19, 19], [19, 20], [19, 21], [19, 22], [19, 23], [19, 24], [19, 25], [19, 26], [19, 27], [19, 28], [19, 29], [19, 30], [19, 31], [19, 32]]
(评论后编辑)
也许这就是你想要的:

if len(ItemList['items'][0]) > 16:
    ItemList['items'][0] = ItemList['items'][0][-16:]

您可以使用以下选项:

ItemList['items'][0] = ItemList['items'][0][16:]
只是:


您可以使用slicingI获得一个解决方案:对于xrange中的x(len(ItemList[“items”][0])/16-1):del ItemList[“items”][0][:16]print ItemList[“items”][0],但这是最好的解决方案?唯一的问题是创建了多个条目​​, 始终在16之前,我想删除前16条记录或获取最后一条记录16@Noa502你的评论和你的问题不一样。在问题中,你说如果有超过16个,那么删除前16个。现在如果有17个元素,删除前16个元素将只剩下1个。但是根据上面的评论,你想得到最后16个。那么你到底想做什么呢?
del ItemList["items"][0][:16]