简体   繁体   中英

How can I automate arithmetic for a list structure in Python?

Input:

['mia', 5, 10]
['mia', 20, 50]
['mia', 52, 101]
['mia', 220, 380]

My code (which works but I'd like to get it automated without typing print by hand all the time):

print lines[1][1] - lines[0][2]
print lines[2][1] - lines[1][2]

Output:

10
2
119

To automate this printing process I tried using a for loop:

for x in lines:
    print lines[x][1] - lines[x-1][2]

And received the error: TypeError: list indices must be integers, not list

Then I tried:

for int(x) in lines:
    print lines[int(x)][1] - lines[int(x)-1][2]

And received the error: SyntaxError: can't assign to function call

I examined Subtracting a value from all elements of a 2D list in python but it did not help me to figure out my problem.

Any help is appreciated to get my arithmetic process automated (either using a for loop so I can understand how I could improve my code above, or some other structure). Bonus points for showing how to define a function or create a class definition to accomplish this task.

In the first case x in lines means x takes the value of each line. Ie, first x = ['mia', 5, 10] , then x = ['mia', 20, 50] ... This isn't what you want. You want x = 0 , x = 1 ...

But by trying to simply making x into an integer by writing int(x) what you are saying is on the first iteration of the loop assign ['mia', 5, 10] to int(x) , and so on. But the left hand side is a function call, meaning take x and convert it to an int , and you can't assign something (a list in this case) to a function call.

What you really want to do is change the right hand side of your looping expression. Instead of going through the list elements you want to go through the list indices .

for x in range(1,len(lines)):
    print lines[x][1] - lines[x-1][2]

尝试此操作,只需将循环语句放入打印语句中,以便\\ n触发

print '\n'.join(str(lines[x][1]-lines[x-1][2]) for x in xrange(1,len(lines)))

You can also go crazy without using range for indices:

for (first, second) in zip(lines[:-1], lines[1:]):
    print second[1] - first[2]

zip or izip (there are slight differences in Python2) create tuples from all iterables that they are given. From the docs:

This function [ zip ] returns a list of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables.

Since the order of lists is guaranteed, this will yield the elements offset by the slices introduced.

Here the first iterable is all the lines without the last and the second iterable is all the lines excluding the first (0 index).

You should do :

for x in range(1,len(lines)):
    #do something

this will loop from 1 to len(lines) - 1

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