回答
压扁你的清单,并然后可以使用max()
内置函数:
l = [2,4,6,[5,10,3]]
def flatten(seq):
for el in seq:
if isinstance(el, list):
yield from flatten(el)
else:
yield el
print(max(flatten(l))) # 10
可以更短/更好,但一个办法:
my_list = [2,4,6,[5,10,3]]
print(max(max(x) if isinstance(x, list) else x for x in my_list))
如果你想支持的只有一个级别flattening,你可以使用'max(max(x)if isinstance(x,list)else x for a)',这会比你的表达式更容易。 –
哦,是的。编辑它是否是适当的做法? –
当然可以。 :) –
为了找到最大值,迭代两次会给我带来额外的开销。首先,将列表展平,然后再次查找最大值。下面是创建一个递归函数返回你嵌套列表的最大值在单次迭代为例:
# The good thing is, you need not to worry about the level of depth
# of the nested list, you can use it on any level of nested list
def get_max(my_list):
m = None
for item in my_list:
if isinstance(item, list):
item = get_max(item)
if not m or m < item:
m = item
return m
采样运行:
>>> my_list = [2,4,6,[5,10,3]]
>>> get_max(my_list)
10
谢谢@moinuddin – jasmine
- 1. list.count(x)在2D列表python
- 2. 在Python中的2D列表
- 3. Python列表,如何找到点除了
- 4. 附加到Python中的2D列表
- 5. Python 3输入到2D列表
- 6. 如何将2D字符串列表转换为2D int列表python?
- 7. python中的类2d列表
- 8. Python 2D阵列团队表
- 9. 2D二进制列表python
- 10. Python打印2D列表
- 11. Python的2D列表排序
- 12. python 2D列表的索引
- 13. 如何打印Python表中的2D列表,如C表
- 14. 的Python:查找在2D列表中的单词并返回是在列表
- 15. 访问在列表2D在Python
- 16. 如何将3D列表转换为Python中的2D列表?
- 17. 如何添加到2D数组列表
- 18. C#在2D阵列中找到2D小阵列
- 19. 在Python中的2D列表操作
- 20. 在Python中复制2D列表
- 21. 在python中计数2d列表
- 22. Python程序找到列表
- 23. 使用python在2D列表中搜索以找到x,y位置
- 24. 如何找到在列表最相似的词在python
- 25. 我如何在python中一次遍历多个2d列表?
- 26. 如何在Python中动态调整2D列表的大小
- 27. 如何在Python 3.4中输入矩阵(2D列表)?
- 28. 如何在Python 2.7中将列添加到2d numpy数组?
- 29. 如何访问Python中2D列表中的列?
- 30. 的Python和2D列表列一致
谢谢!:) @leaf – jasmine