user2242044
user2242044

Reputation: 9213

Splitting a Python list based on criteria

I have a python list as follows:

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: Clearly there are some issues 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])

Upvotes: 3

Views: 1323

Answers (3)

d-coder
d-coder

Reputation: 13953

Instead of writing my own answer I would like to point out where you went wrong with an 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

Upvotes: 0

Sravan K Ghantasala
Sravan K Ghantasala

Reputation: 1318

You can use python's filter for this purpose in the following way.

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

Upvotes: 1

AtAFork
AtAFork

Reputation: 376

You can use list comprehension to achieve this:

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

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

Upvotes: 1

Related Questions