Splitting a Python list based on criteria

I have a python list like this:

mylist = [('Item A','CA','10'),('Item B','CT','12'),('Item C','CA','14')]

      

I would like to split it into a list based on column 2 == 'CA'

Desired output:

filtered_list = [('Item A','CA','10'),('Item C','CA','14')]

      

My attempt: it is clear that there are some problems here!

mylist = [('Item A','CA','10'),('Item B','CT','12'),('Item C','CA','14')]
filtered_list[]
for row in mylist:
    if [row:1] = 'CA'
       filtered_list.append(mylist[row])

      

+3


source to share


3 answers


To achieve this, you can use a list comprehension:



mylist = [('Item A','CA','10'),('Item B','CT','12'),('Item C','CA','14')]

filtered_list = [item for item in mylist if item[1]=='CA']

      

+1


source


You can use a python filter for this purpose as follows.



filtered_list = list(filter(lambda x: x[1] =='CA',mylist)))

      

+1


source


Instead of writing my own answer, I would like to point out where you went wrong with the explanation.

mylist = [('Item A','CA','10'),('Item B','CT','12'),('Item C','CA','14')]
filtered_list[]                         ## I believe this was typo 
for row in mylist:
    if [row:1] = 'CA'                    ## this where you missed it!
       filtered_list.append(mylist[row])

      

I have corrected your code.

mylist = [('Item A','CA','10'),('Item B','CT','12'),('Item C','CA','14')]
filtered_list = []                        ## list created
for row in mylist:
    if row[1] == 'CA':                    ## == for if condition and : 
        filtered_list.append(row)         ## appending the row if row[1] == "CA"
print filtered_list

      

0


source







All Articles