python - selecting the earliest entry in a list -
if have list people's names , dates, , want keep entry earliest date per person how do that? want final list alphabetical last name, first name , contain entry earliest date @ end.
here example of list , tried, gave me same list again.
l1=['smith, john, 1994', 'smith, john, 1996', 'smith, john, 1998', 'smith, joan, 1993', 'smith, joan, 1995', 'smith, jack, 1989', 'smith, jack, 1991', 'jones, adam, 2000', 'jones, adam, 1998', 'jones, sarah, 2002', 'jones, sarah, 2005', 'brady, tom, 2001', 'brady, tonya, 2002'] l1.sort() l2= [] item in l1: if item.split(',')[:2] not in l2: l2.append(item)
the final product should like:
l2=['brady, tom, 2001', 'brady, tonya, 2002', 'jones, adam, 1998', 'jones, sarah, 2002', 'smith, jack, 1989', 'smith, joan, 1993', 'smith, john, 1994']
any or insight appreciated!
try
l1.sort() [next(j) i, j in itertools.groupby(l1, lambda x: x.rsplit(",", 1)[0])]
your code not work since searching l2
item.split(',')[:2]
, name. strings in list consist of name , year -- that's why not in
yields true
.
Comments
Post a Comment