user483144
user483144

Reputation: 1441

Python list manipulation

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.

Upvotes: 0

Views: 1274

Answers (2)

Richard Careaga
Richard Careaga

Reputation: 670

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.

Upvotes: 1

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798606

[x[0][:2] + x[-1][-2:] for x in alist]

Upvotes: 12

Related Questions