I have a problem getting the highest value in a dynamic list of tuple lists.
The list may look like this:
adymlist = [[('name1',1)],[('name2',2),('name3',1), ...('name10', 20)], ...,[('name m',int),..]]
Now I am browsing the list to get the maximum value (integer):
total = {} y=0 while y < len(adymlist): if len(adymlist) == 1: #has the List only 1 Element -> save it in total total[adymlist[y][0][0]] = adymlist[y][0][1] y += 1 else: # here is the problem # iterate through each lists to get the highest Value # and you dont know how long this list can be # safe the highest Value in total fe total = {'name1':1,'name10':20, ..}
I tried a lot to get the maximum value, but I did not find any conclusion about my problem. I know that I have to scroll through each Tuple in the list and compare it with the next, but he does not know how to encode it correctly.
I can also use the max() function, but it does not work with strings and integers. FE a = [ ('a',5),('z',1)] β the result max(a) ---> ('z',1) obv 5> 1, but z> a, so I tried extend the max function with max(a, key=int) , but I get Type Error.
I hope you understand what I want; -)
<strong>
UPDATE
Thanks, bye.
If I use itertools.chain(*adymlist) and max(flatlist, key=lambda x: x[1])
, I will get an exception, for example: max_word = max (flatlist, key = lambda x: x [1]) TypeError: the object 'int' is not subject to subscription
BUT if I use itertools.chain(adymlist) , it works fine. But I do not know how to sum all the integers from each tuple from the list. I need your help to figure this out.
Otherwise, I wrote a workaround for itertools.chain(*adymlist) to get the sum of all integers and the highest integer in this list.
chain = itertools.chain(*adymlist) flatlist = list(chain) # flatlist = string, integer, string, integer, ... max_count = max(flatlist[1:len(flatlist):2]) total_count = sum(flatlist[1:len(flatlist):2]) # index of highest integer idx = flatlist.index(next((n for n in flatlist if n == max_count))) max_keyword = flatlist[idx-1]
He still does what I want, but isn't it dirty?