简体   繁体   中英

How to find a list in a list of lists where the first element is the greatest?

I have a list of lists like this:

a = [[15, 'bane', 'smth'], [13, 'qwe', 'qweqw'], ...]

I need to check for the first element and output the list with the greatest first element.

In this case:

[15, 'bane', 'smth']

I tried using amax from NumPy, but I only need to get the maximum based on the first element and that doesn't work

a = np.amax(a, axis=0)

I get the error

cannot perform reduce with flexible type

because the other elements are strings I suppose. Is there any other method that I can use for this purpose?

I think you can just use the regular old max function, since iterables are compared based on their first element.

a = max(a)

You can use the key parameter in the max function to specify what to use for sorting. As it is the first item, however, simply max(a) should suffice.

>>> max(a, key=lambda sublist: sublist[0])
[15, 'bane', 'smth']

You can just do max(map(lambda x: x[0], a)) to first select the first element of arrays then take the max

You can try the native Python way:

>>> a = [ [15, 'bane', 'smth'] , [13, 'qwe', 'qweqw'], [16, 'aaa', 'bbb'] ]
>>> (sorted(a, key=lambda x: x[0]))[-1]
[16, 'aaa', 'bbb']
>>>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM