Lisa
Lisa

Reputation: 4436

python how to skip an element when slice a list

I want to get [[1,2,4], [11, 12, 14], [21, 22, 24]] from [[1,2,3,4], [11, 12, 13, 14], [21, 22, 23, 24]]. What is an elegant way?

My real problem is a 100000*17 2d list. Thanks.

Upvotes: 0

Views: 2908

Answers (5)

Kiran Poojary
Kiran Poojary

Reputation: 233

Try

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

Output [[ 1 2 4 5] [ 6 7 9 10]]

Upvotes: 0

Ajax1234
Ajax1234

Reputation: 71471

You can use unpacking in Python3:

s = [[1,2,3,4], [11, 12, 13, 14], [21, 22, 23, 24]]
new_s = [a+[b] for *a, _, b in s]

Output:

[[1, 2, 4], [11, 12, 14], [21, 22, 24]]

Upvotes: 0

user6345
user6345

Reputation: 21

One simple way is to pop the index of the element for each sub-list:

>>my_list =  [[1,2,3,4], [11, 12, 13, 14], [21, 22, 23, 24]]

>>for i in my_list:

>>    i.pop(2)

>> 3
>> 13
>> 23
>> print my_list
>> [[1, 2, 4], [11, 12, 14], [21, 22, 24]]

Upvotes: 1

DDGG
DDGG

Reputation: 1241

A straightforward way is:

rows = [[1, 2, 3, 4], [11, 12, 13, 14], [21, 22, 23, 24]]

print([[a, b, d] for a, b, c, d in rows])

or

print([[row[0], row[1], row[3]] for row in rows])

Upvotes: 1

Mateen Ulhaq
Mateen Ulhaq

Reputation: 27271

One way is:

import numpy as np
np.array(lst)[:, (0, 1, 3)]

Upvotes: 3

Related Questions