我正在尝试修改列表.目前,有一个随机数列表,我想更改列表,这将创建数字之间的最大增加数.也许我的措辞很糟糕.例如,如果列表是[2,3,1,2,1],我将修改为[1,2,3,1,2],因为1-> 2,2-> 3和1-> 2增加,总共增加3个序列.有什么建议? 最佳答案 我会用这种递归算法来解决你的问题.我正在做的是整理我的列表,将所有重复项放在最后,并重复相同的排除排序,无重复列表.
def sortAndAppendDuplicates(l):
l.sort()
ll = list(dict.fromkeys(l)) # this is 'l' without duplicates
i = 0
while i < (len(ll)-1):
if list[i] == list[i+1]:
a = list.pop(i)
list.append(a)
i = i - 1
i = i + 1
if hasNoDuplicates(l):
return l
return ll + sortAndAppendDuplicates(l[len(ll):])
def hasNoDuplicates(l):
return( len(l) == len( list(dict.fromkeys(l)) ) )
print(sortAndAppendDuplicates([2,3,6,3,4,5,5,8,7,3,2,1,3,4,5,6,7,7,0,1,2,3,4,4,5,5,6,5,4,3,3,5,1,2,1]))
# this would print [0, 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 3, 4, 5, 3, 5, 3, 5]