Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Categorize list in Python

Tags:

python

list

What is the best way to categorize a list in python?

for example:

totalist is below

totalist[1] = ['A','B','C','D','E']
totalist[2] = ['A','B','X','Y','Z']
totalist[3] = ['A','F','T','U','V']
totalist[4] = ['A','F','M','N','O']

Say I want to get the list where the first two items are ['A','B'], basically list[1] and list[2]. Is there an easy way to get these without iterate one item at a time? Like something like this?

if ['A','B'] in totalist

I know that doesn't work.

like image 764
user1179317 Avatar asked Mar 12 '23 06:03

user1179317


1 Answers

You could check the first two elements of each list.

for totalist in all_lists:
    if totalist[:2] == ['A', 'B']:
        # Do something.

Note: The one-liner solutions suggested by Kasramvd are quite nice too. I found my solution more readable. Though I should say comprehensions are slightly faster than regular for loops. (Which I tested myself.)

like image 174
Rockybilly Avatar answered Mar 13 '23 21:03

Rockybilly