Need max values in list of tuples, based on position

Pancho Pancho.Jones at proton.me
Fri Nov 11 14:22:04 EST 2022


On 11/11/2022 18:53, DFS wrote:
> On 11/11/2022 12:49 PM, Dennis Lee Bieber wrote:
>> On Fri, 11 Nov 2022 02:22:34 -0500, DFS <nospam at dfs.com> declaimed the
>> following:
>>
>>>
>>> [(0,11), (1,1),  (2,1),
>>>   (0,1) , (1,41), (2,2),
>>>   (0,9) , (1,3),  (2,12)]
>>>
>>> The set of values in elements[0] is {0,1,2}
>>>
>>> I want the set of max values in elements[1]: {11,41,12}
>>
>>     Do they have to be IN THAT ORDER?
> 
> Yes.
> 
Sets aren't ordered, which is why I gave my answer as a list. A wrongly 
ordered list, but I thought it rude to point out my own error, as no one 
else had. :-)

Assuming you want numeric order of element[0], rather than first 
occurrence order of the element[0] in the original tuple list. In this 
example, they are both the same.

Here is a corrected version

from collections import OrderedDict
def build_max_dict( tups):
     dict =  OrderedDict()
     for (a,b) in tups:
         if (a in dict):
             if (b>dict[a]):
                 dict[a]=b
         else:
             dict[a]=b
     return(dict.values())

This solution giving the answer as type odict_values. I'm not quite sure 
what this type is, but it seems to be a sequence/iterable/enumerable 
type, whatever the word is in Python.

Caveat: I know very little about Python.






More information about the Python-list mailing list