Python获取第二小元素嵌套列表递归
我想使用递归和无内置函数从嵌套列表返回第二个最小的元素。i、 ePython获取第二小元素嵌套列表递归,python,list,recursion,nested,Python,List,Recursion,Nested,我想使用递归和无内置函数从嵌套列表返回第二个最小的元素。i、 e >>>ss([[[1,3],[2],3]]) 2 我知道如何获取这些列表的最大值和最小值,但我很难跟踪第二个最小值 到目前为止我写的东西,返回正确的最小值,但对次最小值不起作用 def ss(L): smallest = L[0] while type(smallest) == type([]): smallest = smallest[0] second_smallest = smallest
>>>ss([[[1,3],[2],3]])
2
我知道如何获取这些列表的最大值和最小值,但我很难跟踪第二个最小值
到目前为止我写的东西,返回正确的最小值,但对次最小值不起作用
def ss(L):
smallest = L[0]
while type(smallest) == type([]):
smallest = smallest[0]
second_smallest = smallest
for element in L:
if type(element) == type([]):
current = ss(element)
if current > smallest and current < second_smallest:
second_smallest = current
if current < smallest and current < second_smallest:
second_smallest = smallest
smallest = current
else:
if smallest < element and element < second_smallest:
second_smallest = element
if smallest > element and second_smallest > element:
second_smallest = smallest
smallest = element
return second_smallest
def ss(L):
最小值=L[0]
而类型(最小)=类型([]):
最小的=最小的[0]
第二个=最小的
对于L中的元素:
如果类型(元素)=类型([]):
电流=ss(元件)
如果电流>最小值且电流<第二个最小值:
第二个=电流
如果电流<最小值且电流<次最小值:
第二个=最小的
最小=电流
其他:
如果最小<元件和元件<次最小值:
第二个元素=最小元素
如果最小>元素和次最小>元素:
第二个=最小的
最小=元素
返回第二个
有什么方法可以实现这一点,或者我应该寻找一种不同的方法吗?好吧,一旦你解决了平面列表的问题,你就可以编写一个函数来平面化列表:
def secondSmallest(l):
def iterflat(l):
for i in l:
if isinstance(i,(list,tuple)):
yield from iterflat(i)
else:
yield i
def min2(l,m1=float('inf'),m2=float('inf')):
if l==[]: return (m1,m2)
if l[0] > m2: return min2(l[1:],m1,m2)
if l[0] > m1: return min2(l[1:],m1,l[0])
if l[0] < m1: return min2(l[1:],l[0],m1)
return min2(list(iterflat(l)))[1]
下面是一个快速解决方案,它涉及到展平嵌套列表(或元组),然后找到第二个最低值。请注意,此方法将跳过最低值的多个实例。输入[1,1,1,2,3]将返回2。采用列表展平法
if-isinstance(i,list)或isinstance(i,tuple)
-->if-isinstance(i,(list,tuple):
对于展平中的j(i):产生j
-->从展平中产生j
(Python 3.4)
>>> secondSmallest([1,6,3,4,9,4,2,5,3,6,2])
2
>>> secondSmallest([1,6,3,4,9,[4,[9,8,-2,-3]],2,5,3,6,2])
-2
def flatten(container):
for i in container:
if isinstance(i, list) or isinstance(i, tuple):
for j in flatten(i):
yield j
else:
yield i
def ss(container):
tmp = list(set(flatten(container)))
tmp.sort
return tmp[1]
ss([1, 2, [3, 4, [5],[1]], [6, [[[7, 3]]]]])
>> 2