在嵌套列表中找到最小值? [英] Finding lowest value within a nested list?
问题描述
我正在尝试编写一个带有列表的函数,并且可以打印该列表中的最低整数.现在,我试图找出该如何处理嵌套列表的方法,即如果最低编号在这些嵌套列表之一之内,则总体上它将打印该编号.我的代码在这里:
Im trying to write a function that takes a list and can print the lowest integer that is within that list. Now i'm trying to figure out what to do where this works with nested lists that if the lowest number is within one of those nested lists then overall it will print that number. My code is here:
def listMin():
list2 = [3,4,[2,99,8],7]
for i in range (len(list2)):
if type(list2[i]) == type([]):
y=min(i)
list2.append(y)
print "hello"
if len(list2)== 0:
return None
else:
x= min(list2)
print x
listMin()
虽然看起来它应该打印数字2,但它不会打印出数字,并且一旦到达嵌套列表,就会给我一个错误:
while this seems like it should print the number 2 it doesnt and just gives me an error once it reaches the nested list saying:
TypeError: 'int' object is not iterable
ive尝试了多种方法,但是我很难确定为什么这种方法不起作用.
ive tried multiple things but i'm having a hard time as to why this sort of thing isn't working.
推荐答案
嵌套一个深层
在您的示例中,列表仅嵌套一个深度.如果通常是这种情况,请尝试:
Nesting One Deep
In your example, the list is nested only one deep. If this is the case in general, then try:
>>> list2 = [3,4,[2,99,8],7]
>>> min(x if isinstance(x, int) else min(x) for x in list2)
2
任意深度的嵌套
如果允许更深层的嵌套,请定义此递归函数:
Nesting of Arbitrary Depth
If deeper nesting is allowed, define this recursive function:
>>> def rmin(lst): return min(x if isinstance(x, int) else rmin(x) for x in lst)
...
操作中:
>>> rmin(list2)
2
或者,通过更深层的嵌套:
Or, with deeper nesting:
>>> list3 = [3,4,[[2,99],8],7]
>>> rmin(list3)
2
>>> list4 = [3, 4, [[2, [99, 1]], 8], 7]
>>> rmin(list4)
1
工作原理
函数rmin
由单行组成:
return min(x if isinstance(x, int) else rmin(x) for x in lst)
如您所见,这是一个列表理解,它查看列表lst
的每个值x
.
As you can see, this is a list comprehension that looks at every value x
of the list lst
.
让我们将min
的参数分为两部分.第一个是:
Let's divide the argument of min
into two parts. The first is:
x if isinstance(x, int) else rmin(x)
如果x
是整数,则返回x
.否则,它将在x
上调用rmin
.在后一种情况下,rmin
递归查看x
中的每个值并返回最小值.
This returns x
if x
is an integer. Otherwise, it calls rmin
on x
. In the latter case, rmin
recursively looks at every value in x
and returns the minimum.
min
参数的第二部分是:
for x in lst
这只是列表理解的常用方法.依次提取lst
中的每个值,并将其分配给x
.
This is just the usual for a list comprehension. It extracts each value in lst
in turn and assigns it to x
.
这篇关于在嵌套列表中找到最小值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!