user1
user1

Reputation: 4131

Selecting a range of columns in Python without using numpy

I want to extract range of columns. I know how to do that in numpy but I don't want to use numpy slicing operator.

import numpy as np

a = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]
arr = np.array(a)

k = 0

print(arr[k:, k+1]) # --> [2 7]
print([[a[r][n+1] for n in range(0,k+1)] for r in range(k,len(a))][0]) # --> [2]

What's wrong with second statement?

Upvotes: 0

Views: 76

Answers (3)

wjandrea
wjandrea

Reputation: 32997

You're overcomplicating it. Get the rows with a[k:], then get a cell with row[k+1].

>>> [row[k+1] for row in a[k:]]
[2, 7]

Upvotes: 1

user7864386
user7864386

Reputation:

Is this what you're looking for?

cols = [1,2,3] # extract middle 3 columns
cols123 = [[l[col] for col in cols] for l in a]
# [[2, 3, 4], [7, 8, 9]]

Upvotes: 1

Алексей Р
Алексей Р

Reputation: 7627

a = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]
k = 0
print(list(list(zip(*a[k:]))[k+1])) # [2, 7]

Upvotes: 1

Related Questions