简体   繁体   English

Python 在具有未定义整数和浮点数的列表和元素列表中查找最大值

[英]Python find max in list of lists and elements with undefined number of integers and floats

I have a big list of list.我有一个很大的清单。 I am trying to find max and min in it.我试图在其中找到最大值和最小值。 Previous questions on this consists lists with strings and this question is differen.t以前的问题包括带有字符串的列表,这个问题是不同的。

    big_list = [[137.83,81.80,198.56],0.0,[200.37,151.55,165.26, 211.84],
 0.0,[1,2,3],4,[5,6,0,5,7,8],0,[2,1,4,5],[9,1,-2]]

My code:我的代码:

max =  max(list(map(max,boxs_list)))

Present output:当前输出:

TypeError: 'numpy.float64' object is not iterable

You could do the following, using max() and min() with generator expressions, and a check with isinstance() to see if each element is a list or not.您可以执行以下操作,将max()min()与生成器表达式结合使用,并使用isinstance()检查每个元素是否为列表。

>>> min(sl if not isinstance(sl, list) else min(sl) for sl in big_list)
-2
>>> max(sl if not isinstance(sl, list) else max(sl) for sl in big_list)
9

the problem is that you need the list to contain only lists问题是你需要列表只包含列表

np.max(np.concatenate([l if isinstance(l,list) else [l] for l in big_list]))

or或者

max(map(max,[l if isinstance(l,list) else [l] for l in big_list]))

Output输出

9

EDIT: get len of sublist编辑:获取子列表的 len

lens = [len(l) if isinstance(l,list) else 1 for l in big_list]
#[3, 1, 4, 1, 3, 1, 6, 1, 4, 3]

if you only want consider list:如果您只想考虑列表:

#lens = [len(l) if isinstance(l,list) else None for l in big_list]
#[3, None, 4, None, 3, None, 6, None, 4, 3]

We could do as when we got the max:我们可以像获得最大值时那样做:

list(map(len,[l if isinstance(l,list) else [l] for l in big_list]))
#[3, 1, 4, 1, 3, 1, 6, 1, 4, 3]

I think the best way is:我认为最好的方法是:

list(map(lambda x: len(x) if isinstance(x,list) else None ,big_list))
#[3, None, 4, None, 3, None, 6, None, 4, 3]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM