How to get maximum max function

max('str','frt',key=len) 

The max function returns only one row.
How can I make her return both rows?
The length of both lines is the same, so max should return both lines, but only one, so there is a way to return all the maximum elements.

+4
source share
3 answers

You can write this as a list comprehension:

 data = ['str', 'frt'] maxlen = max(map(len, data)) result = [s for s in data if len(s) == maxlen] 
+3
source

By definition, the max function returns the maximum value. It does not return an element, just a unique value (even if there are several elements with the same maximum value). I suggest you use a sorting algorithm and take whatever values ​​you need.

In your example:

 data = ['str','frt'] sorted(data,key=len, reverse=True) result = [s for s in data if len(s)==len(data[0])] 
+3
source

Here's a simple function that does this in one go:

 def maxes(a, key=None): if key is None: key = lambda x: x m, max_list = key(a[0]), [] for s in a: k = key(s) if k > m: m, max_list = k, [s] elif k == m: max_list.append(s) return m, max_list 

In action:

 In [11]: maxes(['a', 'ab', 'a', 'cd'], key=len) Out[11]: (2, ['ab', 'cd']) 

It may or may not be faster than running the list comprehension mentioned by another poster, and of course faster than sorting ... but a little testing tells it faster:

Example line:

 In [20]: a = [''.join(random.choice('abc') for _ in xrange(random.randint(1, 100))) for i in xrange(1000)] In [21]: %timeit maxes(a, key=len) 10000 loops, best of 3: 53 µs per loop In [22]: %timeit m = max(map(len, a)); [s for s in a if len(s) < m] 10000 loops, best of 3: 104 µs per loop In [23]: %timeit sorted_a = sorted(a, key=len, reverse=True); [s for s in a if len(s) == len(sorted_a[0])] 1000 loops, best of 3: 322 µs per loop 

If we look at integers with a key:

 In [30]: a = [random.randint(1, 10000) for i in xrange(1000)] In [31]: %timeit maxes(a, key= lambda x: x**2) 10000 loops, best of 3: 150 µs per loop In [32]: %timeit m = max(a, key=lambda x: x**2); [s for s in a if s**2 < m] 1000 loops, best of 3: 183 µs per loop In [33]: %timeit sorted_a = sorted(a, key=lambda x: x**2, reverse=True); [s for s in a if s ** 2 == sorted_a[0] ** 2] 1000 loops, best of 3: 441 µs per loop 

However, without a key, it is better to understand the list:

 In [34]: %timeit maxes(a) 10000 loops, best of 3: 98.1 µs per loop In [35]: %timeit m = max(a); [s for s in a if s < m] 10000 loops, best of 3: 49.2 µs per loop In [36]: %timeit sorted_a = sorted(a, reverse=True); [s for s in a if s == sorted_a[0]] 10000 loops, best of 3: 152 µs per loop 

This is expected, since the redundant key code is still applied if we try to execute this logic (replace the calls with the key (x) only with x) the function is again a little faster:

 In [37]: %timeit maxes2(a) 10000 loops, best of 3: 39.7 µs per loop 
+2
source

Source: https://habr.com/ru/post/1415242/


All Articles