高级列表理解

Advanced list comprehension

一个整数列表一次输入到程序1中,例如:

[1, 3, 1, 4, 4, 3, 1]

任务:

打印一个列表,其中包含与给定列表完全相同的数字,
但重新排列,以便每 3 后紧跟一个 4。3 不得移动索引位置,但其他每个数字都可以移动。

示例的输出应为:

[1, 3, 4, 1, 1, 3, 4]

到目前为止,我的代码只能完成规则 1 和 2。如何修改我的代码以满足此要求?

newList=[]

n=0

numCount= int(input())

while True:
    try:
        n = int(input())
    except:
        break
    if len(newList) !=(numCount):

        if  n == 3:
            newList.append(3)
            newList.append(4)
        else:
            newList.append(n)

print(newList) 

下面是一个函数:

def arrange_list(my_list):
    # Copy the whole list
    arranged_list=myList.copy()

    # Find the all 4s
    index_of_4s=[i for i, x in enumerate(arranged_list) if x == 4]
    next_4=0

    # Loop over the whole list
    for i in range(len(arrangedList)):
        if(arrangedList[i]==3):  # We only care about 3s

            # We swap the previously found 4 with a 1
            arranged_list[index_of_4s[next_4]]=arranged_list[i+1]
            arranged_list[i+1]=4

            # We target the next 4
            next_4=next_4+1
    return arranged_list

如果我们用你的例子测试它,我们得到:

    myList=[1, 3, 1, 4, 4, 3, 1]
    arrange_list(myList)
    #> [1, 3, 4, 1, 1, 3, 4]

我建议你先获取输入列表中3和4的所有索引,然后将3后面的每个元素与4交换。它给出了以下代码,非常简短且易于阅读:

a = [1, 3, 1, 4, 4, 3, 1]

# Get the indexes of 3 and 4 in the list
indexesOf3 = [i for i,elem in enumerate(a) if elem == 3]
indexesOf4 = [i for i,elem in enumerate(a) if elem == 4]

# Swap each element following a 3 with a 4
for i3,i4 in zip(indexesOf3,indexesOf4):
    a[i3+1], a[i4] = a[i4], a[i3+1]

print(a)
# [1, 3, 4, 1, 1, 3, 4]

注意:此代码示例修改了输入列表,但显然它可以很容易地更新为返回新列表并保持输入列表原样的函数。

你的问题定义的不是很清楚,没有考虑丢失的场景。这段代码的工作非常简单,想法是创建一个新列表。

-找到输入中3的位置

-在新列表中放置 3,然后放置 4

-放置剩余的元素。

input_list = [1, 3, 1, 4, 4, 3, 1]

# Check the number of 3 and 4
n3 = input_list.count(3)
n4 = input_list.count(4)

if n3 > n4:
    for i in range(n3-n4):
        input_list.append(4)
elif n4 > n3:
    for i in range(n4-n3):
        input_list.append(3)

# Now let's look at the order. The 3 should not move and must be followed by a 4.
# Easy way, create a new list.

output_list = [None for i in range(len(input_list))]

# Then I'm using numpy to go faster but the idea is just to extract the ids are which the 3 are placed.
import numpy as np

# Place the 3 and the 4
for elt_3 in np.where(np.asarray(input_list) == 3)[0]:
    output_list[elt_3] = 3
    output_list[elt_3+1] = 4 # Must be sure that the input_list does not end by a 3 !!!

# Then we don't care of the position for the other numbers.
other_numbers = [x for x in input_list if x != 3 and x != 4]

for i, elt in enumerate(output_list):
    if elt is None:
        output_list[i] = other_numbers[0]
        del other_numbers[0]

print (output_list)

在一个更紧凑的单循环版本中,它给出:

input_list = [1, 3, 1, 4, 4, 3, 1]
position_3 = np.where(np.asarray(input_list) == 3)[0]
other_numbers = [x for x in input_list if x != 3 and x != 4] # Not 3 and not 4
output_list = [None for i in range(len(input_list))]

for i, elt in enumerate(output_list):
    if elt == 4:
        continue
    elif i not in position_3:
        output_list[i] = other_numbers[0]
        del other_numbers[0]
    else:
        output_list[i] = 3
        output_list[i+1] = 4