[英]How to compare 2 items from two lists and find the difference position between them?
[英]How can I compare two lists, and find the difference between them?
我正在尝试制作一个程序来打印哪些车开得快,哪些车没有开。 输入是这样的。 1 12:00:03 DX-89-EH 2 12.00.42 DX-89-EH 此列表包含大量车牌,因此我想将它们分成两组。 一个用于传感器一,一个用于传感器二。 之后我想比较时间,并计算它们之间的差异。 然后我可以计算最终速度。 到目前为止,我带着这个:
distance = 200
def speed(line):
max_speed = line
print(max_speed)
def line_information(line):
sensor, time, plate = line.split()
return {"sensor": sensor, "time": time, "plate": plate}
data = []
file = open('traffic_input.txt').read().split('\n')
for counter, line in enumerate(file):
if counter == 0:
speed(line)
else:
data.append(line_information(line))
def elapsed_time(time_start, time_end):
hours, minutes, seconds = time_start.split(":")
time_start_sec = int(hours) * 3600 + int(minutes) * 60 + int(seconds)
hours, minutes, seconds = time_end.split(":")
time_end_sec = int(hours) * 3600 + int(minutes) * 60 + int(seconds)
elapsed_time = time_end_sec - time_start_sec
def speed(kmh):
actual_speed = (distance / elapsed_time) * 3.6
file = open('traffic_input.txt').read().split('\n')
for counter, line in enumerate(file):
if counter == 0:
speed(line)
else:
line_information(line)
有人可以解释一下我可以做些什么来完成这项工作,以及我如何比较这些列表? 致谢。
这在基础 python 中是可能的,但如果你正在做一个更大的项目,我强烈建议使用统计包(特别是numpy
和pandas
)来做到这一点。 这是因为随着数据集的增长,numpy 和 pandas 以比基础 python 更有效的方式存储数据。 (有关更多信息,请参阅本文)。
使用pandas
:
import pandas as pd
fullTime= []
file = open('traffic_input.txt').read().split('\n')
for counter, line in enumerate(file):
data.append(line_information(line))
#create dataframe
data= pd.DataFrame(fullTime)
#split columns into starting time (sensor 1), ending time (sensor 2), and license plate
data["startingTime"] = data[fullTime].split()[1]
data["endingTime"] = data[fullTime].split()[4]
data["licensePlate"] = data[fullTime.split()[2]
#use elapsed time function to create a new column in the dataframe with elapsed time
data["elapsedTime"] = elapsed_time(data["startingTime"], data["endingTime"])
关于熊猫的一些有用链接:
如果您有理由与基础 python 完全结婚,请发表评论,我将进行编辑。 但是对于大多数数据分析任务,python 库让你的生活变得更轻松(即使它们需要一点时间来学习)。
编辑,因为你绑定到基础 python:
我将通过使用格式为[[starting time, endingtime, elapsed time][starting time for car 2, ending time for car 2, elapsed time for car 2], ...]
的列表来解决这个问题,就像这样
timeArr = []
for i in data:
thisRow = [];
startingTime = i[fullTime].split()[1]
endingTime = i[fullTime].split()[4]
thisRow.append([startingTime, endingTime, elapsed_time(startingTime, endingTime)
之后,您可以使用以下命令访问每个车牌的经过时间
for i in timeArr:
print(i[2])
如果您想要某种 ID 来访问它,您甚至可以将车牌号添加到原始数组的一部分。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.