Need max values in list of tuples, based on position
DFS
nospam at dfs.com
Fri Nov 11 14:56:41 EST 2022
On 11/11/2022 7:50 AM, Stefan Ram wrote:
> Pancho <Pancho.Jones at proton.me> writes:
>> def build_max_dict( tups):
>> dict = {}
>> for (a,b) in tups:
>> if (a in dict):
>> if (b>dict[a]):
>> dict[a]=b
>> else:
>> dict[a]=b
>> return(sorted(dict.values()))
>
> Or,
>
> import itertools
> import operator
>
> def build_max_dict( tups ):
> key = operator.itemgetter( 0 )
> groups = itertools.groupby( sorted( tups, key=key ), key )
> return set( map( lambda x: max( x[ 1 ])[ 1 ], groups ))
FYI, neither of those solutions work:
Pancho: 11, 12, 41
You : 41, 11, 12
The answer I'm looking for is 11,41,12
Maybe a tuple with the same info presented differently would be easier
to tackle:
orig:
[(0, 11), (1, 1), (2, 1),
(0, 1), (1, 41), (2, 2),
(0, 9), (1, 3), (2, 12)]
new: [(11,1,1),
(1,41,2),
(9,3,12)]
I'm still looking for the max value in each position across all elements
of the tuple, so the answer is still 11,41,12.
Edit: found a solution online:
-----------------------------------------------------------------
x = [(11,1,1),(1,41,2),(9,3,12)]
maxvals = [0]*len(x[0])
for e in x:
maxvals = [max(w,int(c)) for w,c in zip(maxvals,e)]
print(maxvals)
[11,41,12]
-----------------------------------------------------------------
So now the challenge is making it a one-liner!
Thanks
More information about the Python-list
mailing list