简体   繁体   中英

Python list how to get item from last to first again?

I need to iterate sequentially until I find or maximize. For example:

ds = [1,2,3,4,5,6,7,8,9]
tmp = 3 # start (variable)
max = 5 # maximize (variable)
target = 8

so output: [4,5,6,7,8] Sorry, my english is not good.

As a very simple approach you could index over the concatenation with the same list.
However, from memory point of view certainly not the best solution.

# ds = [1,2,3,4,5,6,7,8,9] 

start = 4
length = 7

res = (ds + ds)[start:start+length]
# [5, 6, 7, 8, 9, 1, 2]

Try:

>>> ds
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> (ds * ((5+6)//len(ds) + 1))[5:5+6]
[6, 7, 8, 9, 1, 2]

Now - 5 is your starting position 5+6 is your end position. You want to iterate over whole data set, as many times to contain end position, so: ((5+6)//len(ds) + 1)

In case if your starting position would be in second, or later repetition (so in your case if it would > 8 . You can move it back by subtracting: (startPosition//len(ds)) * len(ds) from both start position, and end position.

There is a built-in way to do this.

new_data = i[starting_index : ending_index]

You can leave a number blank if you want to get the rest of the list. Like:

>>>i = [0,8,9,4]
>>>i[1:]
[8,9,4]

see this solution i used a for loop to reach your target

ds = [1,2,3,4,5,6,7,8,9]
tmp = 3 # start (variable)
max = 5 # maximize (variable)
target=8
i=0  # itiration to loop on the list
for x in ds: 
    if ds[i]<tmp: #till now we didnt reach start point
        i=i+1
    else:
        print(ds[i]) 
        i=i+1
        if  i == target: #since the target has been reached 
            break

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM