简体   繁体   中英

How to take the nth - (n-1)th term in Python?

I would like to know how to find the nth term - (n-1)th term within a list. I know it should be very simple, but I'm just having trouble with application. So given the input of [0, 2, 4, 6, 5] , the function should return [0, 2, 2, 2, -1] . My solution (which doesn't work) is as follows:

def cost_to_diff (stocks):
    for i in range(i+1):
        stock[i] = stock[i] - stock[i-1]
        print stock

Why doesn't this work as intended?

Your mistake is that you reset the i th element of list, so on the next cycle iteration you access it's changed value.

This will print what you need

def cost_to_diff (stocks):
    for i in range(1, len(stocks)):
        print stocks[i] - stocks[i-1]

If you want to print a list, then do

def cost_to_diff (stocks):
    diff = []
    for i in range(1, len(stocks)):
        diff.append(stocks[i] - stocks[i-1])
    print diff

or

def cost_to_diff (stocks):
    print [stocks[i] - stocks[i-1] for i in range(1, len(stocks))]

Also I advice you to try numpy for such tasks. This function will do the job. Especially if you are playing with stock data, numpy will be much faster than lists. Moreover for stock data one usually uses data frames, so pandas is what you need to study, and Series.diff is the function you need.

You are using the wrong range. You need to find out the length of the stocks list, and then build your range accordingly.

differences = []
for i in range(len(stocks) - 1):
    differences.append(stock[i+1] - stock[i])
    print differences

However, there is a better way to do this. Python has several builtins to help you do this kind of stuff easily. Use the zip function to get your elements without messing around with indexes.

differences = []
for a, b in zip(l, l[:1]):
    differences.append(b-a)

For example:

my_list = [0, 3, 4, 5, 7]
print zip(my_list, my_list[1:])

This produces output

[(0, 3), (3, 4), (4, 5), (5, 7)]

All you need to do after is subtract the elements.

The following code returns [2, 2, 2, -1] because I don't get why you will get 0 for the first element.

Do you assume that the first -1 element is also 0?

len('list') will give you the length of list.

range(start, end) will give you a range.

Since you like to start your iterations in the for loop at the second element ( index = 1 ) start will be 1 and end will be the length of the stock list.

stock = [0,2,4,6,5] 
result = []#create an empty list for the results
for i in range(1,len(stock)):#set the iteration steps, will be 1,2,3,4 in this case
    result.append(stock[i] - stock[i-1])#By using stack[i] = ... you will overwrite the ith element
print result

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