python - Return sublists of List of lists -


well, have example:

mylist = [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]] 

it list of lists. want keep first 5 points of each sublist. if simple list called mylist[:5] , that's all. now, simpliest method imagine iterate through mylist , copy first 5 points of each sublist new list.

newlist = [] in mylist:     newlist.append(i[:5]) 

but happen if list has length 10.000+. know faster way?

well, same using list comprehension @ least bit shorter.

return [x[:5] x in mylist] 

or if making function generator instead, yield individual elements:

for x in mylist:     yield x[:5] 

Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -