假设程序根据“pivot”值移动数字。列表中透视值前面的所有数字都必须小于或等于透视值,透视值后面的所有数字都必须大于透视值(Python(3.x版)
a = [1,4,3,7,4,7,6,3,7,8,9,9,2,5]
print("Original List")
print(a)
pivot = 4 #or select any number from the list
b = list(a)
for i in range(len(a)):
pivotIndex = b.index(pivot) #gives index of pivot through every iteration
if a[i] > pivot:
b.insert(pivotIndex+1,a[i])
elif a[i] <= pivot:
b.insert(0,a[i])
print("New List")
print(b)
问题是,我不知道如何删除原始的数字,一旦它已经被移动,并在这样的列表中,有重复的数据透视值,当一个数字是相等的数据透视它移动到前面,并视为新的数据透视。我是不是走错了路
您可以使用
.pop(index)
获取索引处的值,并通过一个操作将其删除:输出:
索引是基于零的
阅读: list.pop([i])
您可以使用列表理解来创建新列表,并使用
enumerate
来确保只计算在枢轴处没有索引的元素:输出:
相关问题 更多 >
编程相关推荐