python conditional list creation from 2D lists
- by dls
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?