2

In python I have an array of arrays:

[[1,2,3,4,5,6,7,8,6,5,4,3],
 [3,4,5,6,7,8,9,5,3,2,4,2],
 [3,4,5,6,7,8,9,5,3,2,4,2],
 [3,4,5,6,7,8,9,5,3,2,4,2],
 [3,4,5,6,7,8,9,5,3,2,4,2]]

And I want to select for each array in array only firs n elements. For example for n == 4 I will get:

    [[1,2,3,4],
     [3,4,5,6],
     [3,4,5,6],
     [3,4,5,6],
     [3,4,5,6]]

What is the most short code in Python for this?

1
  • 2
    Your question history suggests you may be using NumPy. If so, please make that clear in your question. NumPy arrays and Python lists are very different, and the appropriate ways of working with them are almost nothing alike. Commented Nov 27, 2016 at 9:30

2 Answers 2

1

If you have list of lists then pure python will do:

>>> a = [[1,2,3,4,5,6,7,8,6,5,4,3],
...  [3,4,5,6,7,8,9,5,3,2,4,2],
...  [3,4,5,6,7,8,9,5,3,2,4,2],
...  [3,4,5,6,7,8,9,5,3,2,4,2],
...  [3,4,5,6,7,8,9,5,3,2,4,2]]
>>> [x[:4] for x in a]
[[1, 2, 3, 4], [3, 4, 5, 6], [3, 4, 5, 6], [3, 4, 5, 6], [3, 4, 5, 6]]

If it's numpy arrays you can use numpy indexing:

>>> a
array([[1, 2, 3, 4, 5, 6, 7, 8, 6, 5, 4, 3],
       [3, 4, 5, 6, 7, 8, 9, 5, 3, 2, 4, 2],
       [3, 4, 5, 6, 7, 8, 9, 5, 3, 2, 4, 2],
       [3, 4, 5, 6, 7, 8, 9, 5, 3, 2, 4, 2],
       [3, 4, 5, 6, 7, 8, 9, 5, 3, 2, 4, 2]])
>>> a[:,:4]
array([[1, 2, 3, 4],
       [3, 4, 5, 6],
       [3, 4, 5, 6],
       [3, 4, 5, 6],
       [3, 4, 5, 6]])
Sign up to request clarification or add additional context in comments.

Comments

0

You can use list comprehension:

l = [[1,2,3,4,5,6,7,8,6,5,4,3],
[3,4,5,6,7,8,9,5,3,2,4,2],
[3,4,5,6,7,8,9,5,3,2,4,2],
[3,4,5,6,7,8,9,5,3,2,4,2],
[3,4,5,6,7,8,9,5,3,2,4,2]]

result = [el[:4] for el in l]

Comments

Your Answer

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.