简体   繁体   中英

Subtraction of two items from two lists in for command

I'm fairly new to Python and I still do basic stuff for my ICT course.

I have a task to create a program that catches foreign number plates that are speeding. I have done times of entry and leave, which would be later assigned to 10 different number plates (that bit isn't important).

To save space, I'm trying to use the for command on the Leave and Enter lists hoping to take away Enter's item from Leave's item, to get the time it took for a car to get from Camera A to B in the program.

How can I do it effectively? Here's something I tried, although I know why it's wrong, I can't find a solution anywhere.

 import itertools Enter=[7.12, 7.14, 7.24, 7.45, 7.28, 7.31, 7.18, 7.25, 7.33, 7.38] #A list for the times of cars passing Camera A Leave=[7.56, 7.24, 7.48, 7.52, 7.45, 7.57, 7.22, 7.31, 7.37, 7.41] #A list for the times of cars passing Camera B Timestaken=[] for item in itertools.chain(Leave,Enter): Timestaken.append(item-item) print(Timestaken) 

The result I get is this, definitely because the for command still takes one list's item away from the same item???:

 >>> [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] 

I think you're looking for zip

Enter=[7.12,
       7.14,
       7.24,
       7.45,
       7.28,
       7.31,
       7.18,
       7.25,
       7.33,
       7.38] #A list for the times of cars passing Camera A

Leave=[7.56,
       7.24,
       7.48,
       7.52,
       7.45,
       7.57,
       7.22,
       7.31,
       7.37,
       7.41] #A list for the times of cars passing Camera B

for enter_data, leave_data in zip(Enter, Leave):
    print(leave_data - enter_data)

You can use map:

for interval in map(lambda x, y: y-x, Enter, Leave):
    print interval

Take care this made some weird things for me in python 2.7 when I tried to print the entire list and not one by one (See here Python 2.7.5 error printing list of float numbers )

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