Python Start counting array of length x starting from second item and finishing on the first one

StackOverflow https://stackoverflow.com/questions/13871186

質問

In Python I have an array of length x.

let array = [0, 1, 2, 3, 4, 5]

I want to get from the array above the result like this: [1, 2, 3, 4, 5, 0]

So basically i wan't to skip the first term and loop it after the array ends and stop on the last skipped term. I'm pretty new to python, so couldn't figure it out on on my own + googling didn't help.

Help please, Much appreciated!

役に立ちましたか?

解決

Use slicing and append().

lst = [0, 1, 2, 3, 4, 5]
new_lst = lst[1:]
new_lst.append(lst[0])

You could also use new_lst.extend(lst[:1]), though when the head slice is a single element, append(lst[0]) is probably slightly more efficient, since you don't have to construct another temporary list just to wrap a single value. lst[1:] + list[:1] is probably the worst though, since it has to create yet another throw away list object compared to the extend() version.

他のヒント

I would go with slicing, but another option (which is normally overkill for something this simple is using a collections.deque)

Small example:

>>> e =  [0, 1, 2, 3, 4, 5]
>>> from collections import deque
>>> d = deque(e)
>>> d
deque([0, 1, 2, 3, 4, 5])
>>> d.rotate(1)
>>> d
deque([5, 0, 1, 2, 3, 4])
>>> d.rotate(-2)
>>> d
deque([1, 2, 3, 4, 5, 0])
e =  [0, 1, 2, 3, 4, 5]

e.append(e.pop(0))

Why people don't think immediately to in-place transformations ???

Yet another way, which might be more general. Couldn't think of a good name...

def iterate_from(l, start):
    for i in range(start, len(l)):
        yield l[i]
    for i in range(start):
        yield l[i]

I got the following output:

In [39]: iterate_from(range(7), 3)
Out[39]: <generator object iterate_from at 0x120259b40>

In [40]: list(iterate_from(range(7), 3))
Out[40]: [3, 4, 5, 6, 0, 1, 2]

when you loop thru your list, don't even need new variable for that

for i in my_list[1:] + my_list[:1]:
    print i,

print
for i in my_list:
    print i,

will return:

1 2 3 4 5 0
0 1 2 3 4 5

This way you don't make any changes to original my_list.

Also, take a look over here: Explain Python's slice notation

Use slices to get the portions of the list you are interested in, and then add them together:

>>> lst = [0, 1, 2, 3, 4, 5]
>>> lst[1:] + lst[:1]
[1, 2, 3, 4, 5, 0]

lst[1:] will give you everything from the first index (inclusive) to the end of the list.

lst[:1] will give you everything from the beginning of the list to the first index (exclusive). (This is equivalent to [lst[0]])

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top