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
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]]
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']]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.