该函数接受一个整数列表,并返回一个由相同元素组成的列表,这些元素按照偶数再奇数的顺序排序。我正在努力实现一个递归函数来完成它,尽管我能够使用for循环来解决这个问题。
def sort(lst: list[int]) -> list[int]:
l1 = []
l2 = []
for i in lst:
if i % 2 == 0:
l1.append(i)
else:
l2.append(i)
x = l1 + l2
return x
def eto(lst: list[int]) -> list[int]:
if len(lst) == 1
return lst
else:
y = lst[0]
x = lst[1:]
return(eto(x))
我不知道如何从这里开始。
我想我们可以对奇数重新排序,只要它们在列表的第二部分。我完成了你的提议:
def eto(lst: list[int]) -> list[int]:
if len(lst) <= 1:
return lst
head = lst[0]
tail = lst[1:]
if head % 2 == 0:
return [head] + eto(tail)
return eto(tail) + [head]