Partitioning a list based on values in tuples - Python
What is the best way to go about partitioning a list of tuples in python?
Currently I have a sorted list of tuples, by the second element (a value), and I want to find all values that are repeated at the be开发者_高级运维ginning in an efficient manner.
say:
[ ("tearing", 3), ("me", 3), ("apart", 3), ("lisa", 3),
("denny", 0), ("mark",0) ]
Running it through the function would return
[("tearing", 3), ("me", 3), ("apart", 3), ("lisa", 3)].
But I am not sure how to go about this.
import itertools
import operator
L = [("tearing", 3), ("me", 3), ("apart", 3), ("lisa", 3), ("denny", 0), ("mark",0)]
print list(itertools.groupby(L, operator.itemgetter(1)).next()[1])
# [('tearing', 3), ('me', 3), ('apart', 3), ('lisa', 3)]
But really, there was no need to remind me about that movie.
from itertools import takewhile
L = [("tearing", 3), ("me", 3), ("apart", 3), ("lisa", 3), ("denny", 0), ("mark",0)]
first = L[0][1]
print list(takewhile(lambda x : x[1] == first, L))
a little variant of ignacio's
An alternative to @Ignacio Vazquez-Abrams' answer, using list comprehensions:
>>> data=[ ("tearing", 3), ("me", 3), ("apart", 3), ("lisa", 3), ("denny", 0), ("mark",0) ]
>>> print [x for x in data if x[-1]== data[0][-1]]
[('tearing', 3), ('me', 3), ('apart', 3), ('lisa', 3)]
精彩评论