Nested List: Count, Max, and Min

I have a nested list:

``````data = [[12345678, 14, 1],[135763365, 14, 0],[135763365, 12, 0],[1234, 9, 0]]
``````

where I want to find the max index 1 of all the sublists.

To do this I've created this function:

``````def findBusiestPeriod ():
result = max([item[1] for item in data])
counter = collections.Counter(itertools.chain(*data))
if counter[result] > 2:
# Here's where I want to find the smallest index[0] based on
# the max index[1]

return result
``````

Once I have the max index `1` of the list, I want to check to see if there are duplicates (there are in the example.) If there are duplicates I want to return only the sublist with the smallest index `0`.

How can I do this?

• answered 2018-05-16 05:36

`sorted()` can do that with a key like :

Code:

``````sorted(data, key=lambda x: (-x[1], x[0]))[0]
``````

Test Code:

``````data = [[12345678, 14, 1], [135763365, 14, 0],
[135763365, 12, 0], [1234, 9, 0]]

print(sorted(data, key=lambda x: (-x[1], x[0]))[0])
``````

Results:

``````[12345678, 14, 1]
``````

• answered 2018-05-16 05:41

As someone already shown the `key` parameter of `sorted` function, I want to mention that the `min` and `max` functions also have a `key` parameter.

``````min(data, key=lambda x: (-x[1], x[0]))
``````