How do I truncate a list?
If I have a list and want to truncate it so it is no more than 100 items, ho开发者_开发问答w do I do this?
To modify the list in place (rather than make a shorter copy of the list), use:
del l[100:]
You can use list slicing:
a = a[0:100]
The items[:100]
other mentioned gives you a new list which contains the first 100 items of items
. If you want to modify the list in-place, either use use items[:] = items[:100]
(slice assignment) or while len(items) > 100: items.pop()
del items[100:]
as proposed by Ned Batchelder.
The correct answer is, of course:
>>> x = range(10)
>>> x
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> x = x[:5]
>>> x
[0, 1, 2, 3, 4]
But, importantly, if you're interested in the values above 100 and want to pull them off one by one for whatever reason, you can also use POP()
>>> x = range(10)
>>> x
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> x.pop()
9
>>> x
[0, 1, 2, 3, 4, 5, 6, 7, 8]
You can even specify which element to pull out:
>>> x= range(10,20)
>>> x
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>> x.pop(3)
13
>>> x.pop()
19
>>> x
[10, 11, 12, 14, 15, 16, 17, 18]
>>> x.pop(-1)
18
[10, 11, 12, 14, 15, 16, 17]
This removes individual elements, shortening the list, without copying.
So, an obtuse and yucky answer (but also correct) would be to iterate down. I'm only going down from 12 to 8 for ease of reading here:
>>> x=range(12)
>>> for i in range(len(x), 8, -1):
... y = x.pop()
... print "popping x: ", y, ", x=", x
...
popping x: 11 , x= [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
popping x: 10 , x= [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
popping x: 9 , x= [0, 1, 2, 3, 4, 5, 6, 7, 8]
popping x: 8 , x= [0, 1, 2, 3, 4, 5, 6, 7]
Sure, it's not optimal, but I just ran into a situation where I needed this so I thought I'd share it here (I'm truncating a list when I see the first not-None value).
You can do something like:
truncated = list[:100]
You can use slicing if you don't mind just simply creating a new copy of the list that contains only the elements you want... however this leaves the original list unmodified.
>>> a = [0,1,2,3,4,5,6,7,8,9]
>>> b = a[0:5]
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> b
[0, 1, 2, 3, 4]
If you really want to truncate the original list, just delete the elements you don't want by using slicing with del
>>> del a[5:]
>>> a
[0, 1, 2, 3, 4]
精彩评论