As an input, I get a master list containing child lists (with variable count).
masterList = [[23,12],[34,21],[25,20]]
Number of child lists varies. 3 child lists are shown here, but the number can vary.
I wish to get max of first records and min of second records.
In this case, I know I can hard code like this...
maxNum = max(masterList[0][0], masterList[1][0], masterList[2][0])
How do I write a module for accepting masterList with varying number of child lists and getting max, min?
Thanks.
You can use zip:
masterList = [[23,12],[34,21],[25,20]]
first, second = zip(*masterList)
print(max(first))
print(min(second))
Edit: for data with sublists containing more than two elements, you can use Python3 unpacking to account for the rest:
masterList = [[23,12, 24],[34,21, 23],[25,20, 23, 23]]
first, second, *_ = zip(*masterList)
print(max(first))
print(min(second))
Output:
34
12
I suppose you are looking for a way to get the max of all 0th index and the min of all the 1st index elements.
max_of_first_element = max(masterList, key = lambda x:x[0])[0]
min_of_second_element = min(masterList, key = lambda x:x[1])[1]
if you need the min not for the second element but for the last element always, then :
min_of_last_element = min(masterList, key = lambda x:x[-1])[-1]
Hope this solves your problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With