![](/img/trans.png)
[英]How to find minimum value from a list using while loop at the same time not using min function in python
[英]Recursive function to find the minimum value in a nested list, without using a for loop
我试图通过列表中的每个列表对 go 执行此操作。
def recMin(nestedLis, n=0) :
if len(nestedLis) == 0 :
return None
elif len(nestedLis) == 1 :
return nestedLis
else :
mini = recMin(nestedLis[n][1: ])
smallest = nestedLis[i][0]
if mini < smallest :
smallest = mini
mini = recMin(nestedLis[n + 1][1: ])
return smallest
当我尝试这样的 output 时:
print("Minimum: ", recMin([3, 5, 3, 5, [3, 1, 5, 3], [3, 2, 5]]))
它会返回一个错误,但是,我试图让它打印:
Minimum: 1
如果您有列表列表(如您的问题标题所示):
lst = [[3, 5, 3, 5], [3, 1, 5, 3], [3, 2, 5]]
min(min(lst, key=min))
如果您确实有一个混合了 int 类型和列表类型的不规则列表(如您的示例所示):
import numpy as np
lst = [3, 5, 3, 5, [3, 1, 5, 3], [3, 2, 5]]
np.min([np.min(item) for item in lst])
这是一个适用于嵌套列表的代码(到您想要的任何嵌套级别):
def recMin(nestedLis):
if isinstance(nestedLis, int):
return nestedLis
if len(nestedLis) == 1:
return recMin(nestedLis[0])
if isinstance(nestedLis[0], list):
return min(recMin(nestedLis[0]), recMin(nestedLis[1:]))
if isinstance(nestedLis[0], int):
return min(nestedLis[0], recMin(nestedLis[1:]))
print("Minimum: ", recMin([3, 5, 3, 5, [3, [1], [5, [932, -10], -1], 3], [3, 2, 5]]))
在您的代码中,您绝不会测试列表中的元素本身是否是列表。 以某种形式或其他形式,您将不得不这样做,因为您处理元素的方式会有所不同,具体取决于它是数字还是子列表。 下面是一个示例实现——注意isinstance
测试。
def recMin(nestedLis):
if len(nestedLis) == 0:
return None
first = nestedLis[0]
if isinstance(first, list):
min_first = recMin(first)
else:
min_first = first
if len(nestedLis) == 1:
return min_first
else:
min_others = recMin(nestedLis[1:])
if min_first < min_others:
return min_first
else:
return min_others
print("Minimum: ", recMin([3, 5, 3, 5, [3, 1, 5, 3], [3, 2, 5]]))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.