【问题标题】:How to finding maximum values in list in python without using loops如何在不使用循环的情况下在 python 中的列表中查找最大值
【发布时间】:2018-05-31 09:42:57
【问题描述】:

我正在尝试使用列表推导找到给定数字列表中的两个最大元素。

这是我迄今为止尝试过的。我还尝试使用“过滤器”功能来代替它。

def top_two(l):
    l1 = [lambda x,y:x > y for x in l]
    return l1

我也尝试过类似的方法,但它也不起作用。

def top_two(l):
    l1 = [l[x] for x in range(len(l)) for y in l[x:] if l[x] > y]

任何帮助将不胜感激!

编辑我没想过简单地对它进行排序!我将使用列表推导对其进行排序并提取最大值。谢谢!

【问题讨论】:

  • 你希望我们做你的功课吗?请提出问题的通用解决方案,然后针对具体问题提出具体问题。
  • 我很抱歉!这不是家庭作业问题,只是我想要解决的问题。
  • 你能排序并取最后两个元素吗?或者您是否应该严格使用列表推导
  • 您编辑的内容类似于作业。
  • 十行就足够用python写一个排序函数了

标签: python functional-programming list-comprehension


【解决方案1】:

您可以简单地对列表进行排序并获得最大的两个数字。我从here复制并粘贴冒泡排序代码

def top_two(l):
    for n in range(len(l)-1,0,-1):
        for i in range(n):
            if l[i]>l[i+1]:
                temp = l[i]
                l[i] = l[i+1]
                l[i+1] = temp
    return l[-1],l[-2]

【讨论】:

  • 谢谢,你有个好主意!我想我会尝试使用带有列表推导的快速排序,然后提取最大值。
【解决方案2】:

排序是一种解决方案,但对于长列表,它可能比所需的成本更高,因为它不是线性的。 Python 远不是最优雅的 FP 语言,但您可以使用 reduce 一次性找到最大的元素。

def add_largest_to_pair(pair, num):
    # This function takes a pair and a number and returns a pair made of the two largest of those three
    if pair[1] > num >= pair[0]:
        return (num, pair[1])
    elif num >= pair[1]:
        return (pair[1], num)
    else:
        return pair

def top_two(l):
    return reduce(
        add_largest_to_pair,
        l,
        (float('-inf'), float('-inf'))
    )

这将返回一个包含两个最大值的元组,pair[0] 是第二大的,pair[1] 是最大的。请注意,这假设您的列表至少有两个长度。

注意:如果您使用的是 Python3,则必须使用 functools.reduce

【讨论】:

    猜你喜欢
    • 2021-11-06
    • 2015-04-24
    • 1970-01-01
    • 2014-11-29
    • 2013-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-12
    相关资源
    最近更新 更多