catris25
catris25

Reputation: 1303

How do I get the max values of tuples that are next to each other in Python?

Say I have the following tuples.

dummy = [("text", 10), ("This is the Sentence", 20), 
         ("that I Want", 20), ("to Get", 20), 
         ("text", 8), ("text", 6)]

I want to get that "This is the Sentence that I Want to Get" and ignore the rest. The text in particular always have the largest value (in this case it's 20) and they're next to each other. Basically, it will only collect the tuples with max values that are next to each other.

With the following code I only collect the first max tuple, but it ignores the rest.

from operator import itemgetter

max(dummy, key=itemgetter(1))

How do I make it that it will get all other max values?

Upvotes: 0

Views: 91

Answers (7)

Ritwik G
Ritwik G

Reputation: 416

My initial assumption seems to be wrong. Don't consider the implementations mentioned in this answers. Leaving this here for informational purpose.

Most answers here use sort or max or similar ways which results in iterating through the data twice. Which is unnecessary I believe. Check the below implementation you should get your desired output with a single iteration through data.

And the answers I have added seems to be performing worse. Especially the answer 2 using string. I believe culprit might be reassigning the string every time.

Also the list comprehension seems to be performing far better than appending. Making the answer 1 also comparatively slower to some other answers.

To verify these you may try this code snippet https://gist.github.com/RitwikGopi/1b36a900219e7c087c95baa99fdf65e2#file-test-py

answer 1:

dummy = [("text", 10), ("This is the Sentence", 20),
         ("that I Want", 20), ("to Get", 20),
         ("text", 8), ("text", 6)]

max_val = float("-inf")
max_data = []

for data, value in dummy:
    if value > max_val:
        max_val = value
        max_data = [data]
    elif value == max_val:
        max_data.append(data)
    else:
        continue

print(max_data)

answer 2:

dummy = [("text", 10), ("This is the Sentence", 20),
         ("that I Want", 20), ("to Get", 20),
         ("text", 8), ("text", 6)]

max_val = float("-inf")
max_data = ""

for data, value in dummy:
    if value > max_val:
        max_val = value
        max_data = data
    elif value == max_val:
        max_data += " " + data
    else:
        continue

print(max_data)

Upvotes: 0

piterbarg
piterbarg

Reputation: 8219

Why not a Pandas one-liner? With a walrus operator as a bonus

import pandas as pd

' '.join((df :=pd.DataFrame(dummy)).loc[df[1] == max(df[1]),0])

output

'This is the Sentence that I Want to Get'

Upvotes: 0

user8060120
user8060120

Reputation:

why not: get the max key using dict values and implement filter by it

m_value = max(dict(dummy).values())
" ".join([x for x, n in dummy if n == m_value])

my result is:

'This is the Sentence that I Want to Get'

Upvotes: 3

pytness
pytness

Reputation: 387

Here's my approach:

from operator import itemgetter

dummy = [("text", 10), ("This is the Sentence", 20), 
         ("that I Want", 20), ("to Get", 20), 
         ("text", 8), ("text", 6)]

max_num = max(dummy, key=itemgetter(1))[1]
text_blocks = [text for text, num in dummy if num == max_num]

sentence = ' '.join(text_blocks)

print(sentence)

# This is the Sentence that I Want to Get

You could improve the code further by using namedtuples as your dummy's items

Upvotes: 1

MSS
MSS

Reputation: 3623

This will work for you.

from operator import itemgetter
# find the max value
max_sen, max_val = max(dummy, key=itemgetter(1))
# filter based on max value and join
" ". join([x[0] for x in filter(lambda x:x[1]==max_val, dummy)])

Upvotes: 0

sammy
sammy

Reputation: 437

[i for i, j in dict(dummy).items() if j==max(dict(dummy).values())]

This would give the max values

example result =

['This is the Sentence', 'that I Want', 'to Get']

Upvotes: -1

sams-studio
sams-studio

Reputation: 733

Something like this?

>>> t = np.array([d[0] for d in dummy])
>>> v = np.array([d[1] for d in dummy])
>>> print(t[v==v.max()])

['This is the Sentence' 'that I Want' 'to Get']

Upvotes: 1

Related Questions