程序被认为是根据“轴心”值移动数字的。列表中枢轴值前面的所有数字都需要小于或等于枢轴值,并且枢轴值后面的所有数字都大于枢轴值。(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)
问题是,一旦移动了原始数字,我就不知道如何删除它,在这样的列表中,有两个枢轴值的副本,当出现一个等于枢轴值的数字时,它会将它移到前面,并将其视为新的枢轴值。我是不是走错路了?
发布于 2018-04-05 04:58:27
您可以使用列表理解来创建新列表,并使用enumerate
来确保只计算在透视表处没有索引的元素:
a = [1,4,3,7,4,7,6,3,7,8,9,9,2,5]
pivot = 4
new_l = [c for i, c in enumerate(a) if c > a[pivot] and i != pivot] + [a[pivot]]+[c for i, c in enumerate(a) if c <= a[pivot] and i != pivot]
输出:
[7, 7, 6, 7, 8, 9, 9, 5, 4, 1, 4, 3, 3, 2
发布于 2018-04-05 05:00:57
您可以使用.pop(index)
获取索引处的值,然后通过一个操作删除它:
numbers = [2,3,4,5,7]
print(numbers)
n = numbers.pop(2)
print (n)
print (numbers)
输出:
[2, 3, 4, 5, 7]
4
[2, 3, 5, 7]
索引是从零开始的。
移除列表中给定位置的项,然后返回它。如果未指定索引,a.pop()将移除并返回列表中的最后一项。(方法签名中i周围的方括号表示该参数是可选的,而不是您应该在该位置键入方括号。您将在Python Library参考中经常看到这种表示法。)
https://stackoverflow.com/questions/49660249
复制相似问题