Reputation: 1293
Consider a list of lists, like this:
my_list = [[0,"zero"], [0,"zero 2x"], [1,"one"], [2,"two"]]
What is the most efficient way to get a subset based on the first value? I want to get:
zero_list = ["zero", "zero 2x"]
Of course one could iterate the whole list, but with a few thousand values it seems inefficient.
zero_list = []
for i in my_list:
if i[0] == 0:
zero_list.append(i[1])
Is there a more efficient way? Would a lambda expression can do this?
Upvotes: 1
Views: 2103
Reputation: 907
Simple solution: If you want to get all elements from the list without iteration, and you can fetch all elements at once from the list as it's separate original data type (not list as an ouput again) then below is the better solution:
my_list=[1,2,3,4]
print(*my_list)
Output: 1 2 3 4
You can use *listname, which will produce all elements from the list separate
Upvotes: 1
Reputation: 29
you can transform the list to DataFrame and extract target values:
df = pd.DataFrame(my_list, columns= ['value', 'char'])
df1 = df[df['value'] == 0].reset_index(drop=True)
Upvotes: 0