Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
171 views
in Technique[技术] by (71.8m points)

python - Swapping list with index

Just want to ask how do i swap the list at the index with the list that follows it and if the list at the index is on the bottom, swap that with the top. So that the index would swap places with the position the list is with the next number For example Normal = [1,2,3,4] and index of 1 would turn to = [1, 3, 2, 4]. making the 2 and 3 swap places and index of 3 would make [4, 2, 3, 1]

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
def swap(lst, swap_index):
    try:
        next_index = (swap_index + 1) % len(lst)
        lst[swap_index], lst[next_index] = lst[next_index], lst[swap_index]
    except IndexError:
        print "index out of range"
lst = [1,2,3,4]
swap_index = 4
swap(lst,swap_index)
print lst

pay attention that everything in Python is reference, that is to say, the swap function swap elements in place


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...