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
183 views
in Technique[技术] by (71.8m points)

list - Is there an easier way to shift an array to the left in python?

I was doing a simple problem in python of shifting an array to the left using python 3.0 for the problem I have I only need to have a length of 3 for the array. For example if my array is [1, 2, 3] after the shift it should read [2,3,1]. My code works but I was wondering if anyone could guide me to making it more efficient, as well as doing it for any array length if possible. My issue is that I don't think I know how to shift all the elements at once, instead I shift all the elements after the first element, and then I append the first element to the array after the loop.

def rotate_left3(nums):
    shifted_nums=[]
    i=len(nums)
    for j in range(i):
        shifted_nums=nums[j-1:]
    var=nums[0]
    shifted_nums.append(var)
    return shifted_nums
question from:https://stackoverflow.com/questions/65902059/is-there-an-easier-way-to-shift-an-array-to-the-left-in-python

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

1 Reply

0 votes
by (71.8m points)

What about this? simply copy the array without the first element first.

def rotate_left3(nums):
  shifted_nums = nums[1:]
  shifted_nums.append(nums[0])
  return shifted_nums

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

...