Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python - processing parent list containing child lists (with variable count)

Tags:

python

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.

like image 369
Vineet Avatar asked Jun 02 '26 22:06

Vineet


2 Answers

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
like image 185
Ajax1234 Avatar answered Jun 05 '26 11:06

Ajax1234


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.

like image 34
Kenstars Avatar answered Jun 05 '26 12:06

Kenstars



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!