I've got a python list
alist = [ [0, 4, 5, 5], [2, 2, 4, 5], [6, 7, 8,13]], [ [3, 4, 5, 5], [2, 2, 4, 5], [6, 7, 8,999] ]
I need the result is
alist = [[0,4,8,13], [3, 4, 8, 999]]
It means first two and last two numbers in each alist element.
I need a fast way to do this as the list could be huge.
asked Oct 24, 2010 at 1:14
user483144
1,4414 gold badges14 silver badges13 bronze badges
-
1What bizarre data structure are you modelling?Daenyth– Daenyth2010年10月24日 02:06:08 +00:00Commented Oct 24, 2010 at 2:06
-
1I'll bet this is homework. Only they left off the [Homework] tag. It's easier to ask here than to think.S.Lott– S.Lott2010年10月24日 03:29:23 +00:00Commented Oct 24, 2010 at 3:29
2 Answers 2
[x[0][:2] + x[-1][-2:] for x in alist]
answered Oct 24, 2010 at 1:16
Ignacio Vazquez-Abrams
804k160 gold badges1.4k silver badges1.4k bronze badges
Sign up to request clarification or add additional context in comments.
Comments
The object is actually a tuple, rather than a list. This can trip you up if you're expecting it to be mutable and it's hard to read. Consider using the continuation character \ for long lines:
alist = [ [0, 4, 5, 5], [2, 2, 4, 5], [6, 7, 8,13]], [ [3, 4, 5, 5], [2, 2, 4, 5], [6, 7, 8, 999] ]
is clearer as
alist = [ [0, 4, 5, 5], [2, 2, 4, 5], [6, 7, 8,13]], \
[ [3, 4, 5, 5], [2, 2, 4, 5], [6, 7, 8, 999] ]
which also helps you spot the double bracket that makes this a tuple. For a list:
alist = [ [0, 4, 5, 5], [2, 2, 4, 5], [6, 7, 8,13], \
[ [3, 4, 5, 5], [2, 2, 4, 5], [6, 7, 8, 999] ]]
If list comprehension as suggested in Javier's answer doesn't meet your speed requirement, consider a numpy array.
answered Oct 24, 2010 at 3:15
Richard Careaga
6751 gold badge5 silver badges11 bronze badges
Comments
lang-py