问题描述
所以我有一个包含几个列表的列表,其中首先有三个字符串,然后是一个浮点数, resultlist = [[1,1,a,8.3931,[1,2,b,6.3231],[2,1,c,9.1931] ]
如何创建一个返回最大值的函数(这里是9.1931)?我试过了:
pre $ def MaxValue():
max_value = max(resultlist)
return max_value
但这只是给了我一个列表。
编辑:另外,我可以通过任何方式获得值来自哪里的索引?从哪个子列表开始?
循环访问外部列表并选择每个子列表的最后一个元素:
pre $
def max_value(inputlist):
返回最大值([输入列表中子列表的子列表[-1]])
print max_value(resultlist)
#9.1931
如果您保留所有功能(将列表作为参数传递,不要通过重用变量名称来混淆名称空间)。
So I have a list that contains several list which all have three strings first, then one float number, like:
resultlist = [["1", "1", "a", 8.3931], ["1", "2", "b", 6.3231], ["2", "1", "c", 9.1931]]
How do I make a function that returns the maximum value (which here would be 9.1931)? I tried
def MaxValue():
max_value = max(resultlist)
return max_value
but that just gives me a list.
EDIT: Also, any way I could get the index for where the value comes from? Like, from which sublist?
Loop through your outer list and select the last element of each sublist:
def max_value(inputlist):
return max([sublist[-1] for sublist in inputlist])
print max_value(resultlist)
# 9.1931
It's also best if you keep all function related variables in-scope (pass the list as an argument and don't confuse the namespace by reusing variable names).
这篇关于从列表中获取最大值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!