根据条件在列表中移动数字

2024-09-27 00:16:38 发布

您现在位置:Python中文网/ 问答频道 /正文

假设程序根据“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)

问题是,我不知道如何删除原始的数字,一旦它已经被移动,并在这样的列表中,有重复的数据透视值,当一个数字是相等的数据透视它移动到前面,并视为新的数据透视。我是不是走错了路


Tags: or数据程序列表indexany数字select
2条回答

您可以使用.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]

索引是基于零的

阅读: list.pop([i])

Remove the item at the given position in the list, and return it. If no index is specified, a.pop() removes and returns the last item in the list. (The square brackets around the i in the method signature denote that the parameter is optional, not that you should type square brackets at that position. You will see this notation frequently in the Python Library Reference.)

您可以使用列表理解来创建新列表,并使用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

相关问题 更多 >

    热门问题