Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...