I have a nested list:
nested_list = [['a', 3], ['a', 1], ['a', 5]]
How do I iterate over this list, select the sublist with the max integer value?
holder = []
for entry in nested_list:
tmp = sublist with max entry[2] value
holder.append(tmp)
I am stuck on coding the second line.
try:
or
If the first item will always be
'a', you can just doIf you’re willing to dive into some type checking and you want to do this for arbitrary sublists (Of one level only. something like [12, ‘a’, 12, 42, ‘b’]), you can do something like.
In any case, if you’re not sure that the elements of
nested_listare in fact lists, you can doand just pass it a key function of your own devising or one of the other ones in this answer.
In terms of the
lambda x: x[1]vs.operator.itemgetter(1)question, I would profile. In princible,itemgettershould be the one right way but I’ve seenoperatorsolutions get outperformed by lambda function do to ‘bugs’ (I use the term loosely, the code still works) inoperator. My preference would be foritemgetterif performance doesn’t matter (and probably if it does) but some people like to avoid the extraimport.