Reputation: 43
I have two lists of numbers and I want a function to return the list with the largest number i.e with two lists [1,2,3,9]
and [4,5,6,7,8]
, the function should return [1,2,3,9]
.
I know for a fact that this works:
a = [1,2,3,9]
b = [4,5,6,7,8]
ans = [_ for _ in [a,b] if max(_) == max((max(a),max(b)))][0]
I know that there is:
a = [1,2,3,9]
b = [4,5,6,7,8]
if max(a)>max(b):
ans = a
else:
ans = b
But is there a more efficient one or two line solution?
Upvotes: 4
Views: 157
Reputation: 7743
This would work
max([a,b], key=max)
The trick here is to know that the max
function can be applied to objects which do not have a natural numerical interpretation, using a key
function.
Upvotes: 0
Reputation: 42143
The max function allows you to specify a key. You can supply the two lists as a list of lists to max() and use max as the key function. This will give yout the result with a very compact statement:
a = [1,2,3,9]
b = [4,5,6,7,8]
result = max([a,b],key=max)
Upvotes: 3
Reputation: 3930
I would recommend numpy or pandas but your solution looks good to be honest.
Here is a numpy example (typing on phone so not tested)
npa = np.array(a)
npb = np.array(b)
max_array = None
total_max = 0 # or -np.inf if you want to deal with negative numbers too
for k in [npa, npb]:
if k.max() > total_max:
max_array = k
Upvotes: 0
Reputation: 39042
How about using the following without any for loop. Just compare the max
of lists
a = [1,2,3,9]
b = [4,5,6,7,8]
ans = (a if max(a) > max(b) else b)
# [1, 2, 3, 9]
Upvotes: 9