查找具有多个相同值的元组的最大值

时间:2019-02-27 03:57:50

标签: python

我有一个元组列表,我需要在右侧找到具有最大值的元组。我还需要程序打印出具有此最大值的每个元组。我试过使用lambda,但是只返回左侧具有最大值的元组之一。具体来说,我尝试过:

Item.where(session: @user.sessions)

哪个返回max(TotalFriendsList,key=lambda x:x[1])

这是列表:

(1,3)

这是我需要的输出:

[(0, 2),
 (1, 3),
 (2, 3),
 (3, 3),
 (4, 2),
 (5, 3),
 (6, 2),
 (7, 2),
 (8, 3),
 (9, 1)]

谢谢!

3 个答案:

答案 0 :(得分:0)

现在,经过优化后,此列表将只遍历列表一次:

data = [(0, 2),
 (1, 3),
 (2, 3),
 (3, 3),
 (4, 2),
 (5, 3),
 (6, 2),
 (7, 2),
 (8, 3),
 (9, 1)]

maxVal = -1
result = None

for datum in data:
    val = datum[1]
    if val > maxVal:
        result = [datum]
        maxVal = val
    elif val == maxVal:
        result.append(datum)

print result

print

# and the way he wanted it printed...
print "[" + ",\n".join([str(v) for v in result]) + "]"

请注意,由于第一个条目包含“获胜元组”,因此该代码根本不会处理失败者。它只是为它们做一些比较,而比较几乎没有花费。因此,基本上它只需一次就可以完成构建结果列表的最少工作量。如果第一个元组不是赢家,那就没有效率了。

输出:

[(1, 3), (2, 3), (3, 3), (5, 3), (8, 3)]

[(1, 3),
(2, 3),
(3, 3),
(5, 3),
(8, 3)]

只有我按照那个人的要求做了;)(tic)-所有答案都正确,...对解决相同问题的不同方式具有很好的见识

答案 1 :(得分:0)

您可以通过获取最大值,然后获取对应的元组来保持紧凑性:

l = [(0, 2),
     (1, 3),
     (2, 3),
     (3, 3),
     (4, 2),
     (5, 3),
     (6, 2),
     (7, 2),
     (8, 3),
     (9, 1)]

# pass a generator expression to `max`
greatest = max(item[1] for item in l)

# "filter" `l`, keeping only tuples that have the greatest value as their second element
result = [item for item in l if item[1] == greatest]
print(result)
# [(1, 3), (2, 3), (3, 3), (5, 3), (8, 3)]

答案 2 :(得分:0)

>>> lst = [(0, 2),
...  (1, 3),
...  (2, 3),
...  (3, 3),
...  (4, 2),
...  (5, 3),
...  (6, 2),
...  (7, 2),
...  (8, 3),
...  (9, 1)]
>>> mx = max(lst, key=lambda x: x[1])
>>> filter(lambda x: x[1] == mx[1], lst)
[(1, 3), (2, 3), (3, 3), (5, 3), (8, 3)]