我如何在Python中反转列表的一部分?在每一步中,我们反转列表的间隔并输出整个列表

问题描述 投票:1回答:2

在每一步,我们反转列表的间隔并输出整个列表。

输入:

3: number of member of list
1 2 3 :list's members
3 :number of indexes of list
2 3: index
2 2: index
2 3: index

输出:

1 3 2
1 3 2
1 2 3

代码:

n=int(input())
a = [i for i in map(int,input().split())]
q=int(input())
for i in range(1,q+1):
    l=[i for i in map(int,input().split())]
    a[::-1]
    print(a)
python slice reverse
2个回答
0
投票

我想你可能想做这样的事情,

mem = int(input("Number of members: "))
members = [int(i) for i in input("List members: ").split()]
idx = int(input("Number of indexes: "))
indexes = [tuple(map(int, input("index: ").split())) for i in range(idx)]

for a, b in indexes:
    members[a - 1], members[b - 1] = members[b - 1], members[a - 1]
    print(members)

输入:

Number of members: 3
List members: 1 2 3
Number of indexes: 3
index: 2 3
index: 2 2
index: 2 3

输出:

[1, 3, 2]
[1, 3, 2]
[1, 2, 3]

0
投票

根据我对标题的了解:

如何在Python中反转列表切片?在每一步中,我们将列表的间隔并输出整个列表

您想从列表中反转一个子序列,这是一个如何做的例子:

my_list = [1, 2, 3, 4, 5]
start, stop = 1, 4

my_list[start: stop] = my_list[start: stop][::-1]

print(my_list)

输出:

[1, 4, 3, 2, 5]
© www.soinside.com 2019 - 2024. All rights reserved.