如何获得Python中相邻元组的最大值?

2024-09-29 21:51:21 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有下面的元组

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

我想得到“This is the Sentence that I Want to Get”,然后忽略其余部分。特别是文本总是具有最大值(在本例中为20),并且它们彼此相邻。基本上,它将只收集彼此相邻的具有最大值的元组

在下面的代码中,我只收集第一个max元组,但它忽略了其余的

from operator import itemgetter

max(dummy, key=itemgetter(1))

如何使其获得所有其他最大值


Tags: thetotext文本getthatisthis
3条回答

以下是我的方法:

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

通过使用namedtuples作为虚拟项,可以进一步改进代码

为什么不: 使用dict值获取max键并通过它实现过滤器

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

我的结果是:

'This is the Sentence that I Want to Get'

像这样的

>>> 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']

相关问题 更多 >

    热门问题