0

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
2
  • 1
    What bizarre data structure are you modelling? Commented Oct 24, 2010 at 2:06
  • 1
    I'll bet this is homework. Only they left off the [Homework] tag. It's easier to ask here than to think. Commented Oct 24, 2010 at 3:29

2 Answers 2

12
[x[0][:2] + x[-1][-2:] for x in alist]
answered Oct 24, 2010 at 1:16
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.