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
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 to share