user7074495
user7074495

Reputation:

Python removing elements from a 2d array depending on first item

If I were to have a 2d array in python, say

lst = [['a','1', '2'], ['b', 1, 2], ['c', 1, 2], ['b', 3, 4]]

I'd like a way to remove any items from lst where the first item is 'b', so that you return with:

[['a','1', '2'], ['c', 1, 2]]

Any help would be greatly appreciated, preferred if only built in libraries are used. Thanks

Upvotes: 1

Views: 234

Answers (2)

akilat90
akilat90

Reputation: 5696

Not using an inbuilt library, but would probably be faster if the array is large,

import numpy as np

lst = np.array(lst)
a = lst[np.where(lst[:,0] != 'b')]
a.to_list()

[['a', '1', '2'], ['c', '1', '2']]

Upvotes: 0

Patrick Haugh
Patrick Haugh

Reputation: 60974

Use a list comprehension

lst = [['a','1', '2'], ['b', 1, 2], ['c', 1, 2], ['b', 3, 4]]
lst = [x for x in lst if x[0] != 'b']
print(lst)

prints

[['a', '1', '2'], ['c', 1, 2]]

Upvotes: 3

Related Questions