python conditional list creation from 2D lists

Posted by dls on Stack Overflow See other posts from Stack Overflow or by dls
Published on 2011-01-01T21:57:53Z Indexed on 2011/01/02 10:53 UTC
Read the original article Hit count: 255

Filed under:
|

Say I've got a list of lists. Say the inner list of three elements in size and looks like this:

['apple', 'fruit', 1.23]

The outer list looks like this

data = [['apple', 'fruit', 1.23],
        ['pear', 'fruit', 2.34],
        ['lettuce', 'vegetable', 3.45]]

I want to iterate through the outer list and cull data for a temporary list only in the case that element 1 matches some keyword (aka: 'fruit'). So, if I'm matching fruit, I would end up with this:

tempList = [('apple', 1.23), ('pear', 2.34)]

This is one way to accomplish this:

tempList = []
for i in data:
   if i[1] == 'fruit':
      tempList.append(i[0], i[2])

is there some 'Pythonic' way to do this in fewer lines?

© Stack Overflow or respective owner

Related posts about python

Related posts about list