[英]How to finding maximum values in list in python without using loops
我正在尝试使用列表理解来找到给定数字列表的两个最大元素。
到目前为止,这是我尝试过的。 我还尝试使用“过滤器”功能代替此功能。
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]
任何帮助,将不胜感激!
编辑我没有想到只是对其进行排序! 我将使用列表推导对它进行排序并提取最大值。 谢谢!
您可以简单地对列表进行排序并获得最大的两个数字。 我从这里复制并粘贴气泡排序代码
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]
排序是一种解决方案,但是对于长列表而言,由于它不是线性的,因此可能比所需的更为昂贵。 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]
为最大。 请注意,这是假设您的列表长度至少为2。
注意 :如果使用的是Python3,则必须使用functools.reduce
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.