如何根据相关值获取最大项目? [英] How to get the max item based on a dependent value?
本文介绍了如何根据相关值获取最大项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个数组:
array = ["a\nb", "c", "d"]
我想找出哪个数组的元素有更多行以及多少行.我想要python中的ruby代码:
I want to find out which array's element has more lines and how many. I want this ruby code in python:
array.map {|e| e.split("\n").size }.max #=> 2
这可行,但是我想知道是否有更好的方法:
This works, but I want to know if there's a better way:
bigger = 0
for e in array:
e_lines = len(e.split('\n'))
if e_lines > bigger:
bigger = e_lines
推荐答案
In [54]: array = ["a\nb", "c", "d"]
In [56]: max(e.count("\n") for e in array)+1
Out[56]: 2
如果您还希望具有最大行数的(可能是非唯一的)元素:
If you also want a (possibly non-unique) element with the maximum number of lines:
In [60]: max((e.count("\n")+1, e) for e in array)
Out[60]: (2, 'a\nb')
这篇关于如何根据相关值获取最大项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文