[英]Recursive function to find the minimum value in a nested list, without using a for loop
I tried to do this to go through each list within the list.我试图通过列表中的每个列表对 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
When I try an output like this:当我尝试这样的 output 时:
print("Minimum: ", recMin([3, 5, 3, 5, [3, 1, 5, 3], [3, 2, 5]]))
It will return an error, however, I am trying to get it to print:它会返回一个错误,但是,我试图让它打印:
Minimum: 1
If you have a list of lists (as your question title suggests):如果您有列表列表(如您的问题标题所示):
lst = [[3, 5, 3, 5], [3, 1, 5, 3], [3, 2, 5]]
min(min(lst, key=min))
If you have indeed an irregular list (as shown in your example) with int types and list types mixed:如果您确实有一个混合了 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])
Here's a code that works with nested lists (to whatever nesting level you want):这是一个适用于嵌套列表的代码(到您想要的任何嵌套级别):
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]]))
At no point in your code are you testing whether the elements on the list are themselves lists or not.在您的代码中,您绝不会测试列表中的元素本身是否是列表。 In some form or other, you are going to have to do that, because how you then treat the elements will differ depending whether it is a number or a sublist.
以某种形式或其他形式,您将不得不这样做,因为您处理元素的方式会有所不同,具体取决于它是数字还是子列表。 Below is an example implementation -- note the
isinstance
test.下面是一个示例实现——注意
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.