-1

int のリストは、一度に 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) 
4

3 に答える 3

0

まさにそれを行う関数は次のとおりです。

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]
于 2018-08-08T08:50:47.573 に答える