python conditional list creation from 2D lists
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?
[(i, k) for i, j, k in data if j == 'fruit']
List comprehensions, using tuple indexing or slicing
tempList = [(i[0], i[2]) for i in data if i[1] == 'fruit']
tempList = [i[:1]+i[2:] for i in data if i[1] == 'fruit']
Also, generator expressions if you don't need a list, just the sequence. (here with tuple unpacking)
>>> tempListGen = ((a,c) for a,b,c in data if b == 'fruit')
>>> tempListGen
<generator object <genexpr> at 0x0266FD50>
>>> print sorted(tempListGen)
[('apple', 1.23), ('pear', 2.34)]
(tested with Python 2.7)
Tuple assignment could make the code easier to understand, paired with a list comprehension for compactness:
tempList = [(item, price) for item, kind, price in data if kind == 'fruit']
The List Comprehension!
tempList = [(i[0], i[2]) for i in data if i[1] == 'fruit']
Will give the same result in fewer lines and will probably execute faster.
[[x[0], x[2]] for x in data if x[1] == 'fruit']
精彩评论