Home > Net >  Function, for-loop, calculate nr of cars at certain speed, 2d list
Function, for-loop, calculate nr of cars at certain speed, 2d list

Time:07-28

I am trying to create a function that calculates the total nr. of cars that pass a checkpoint at each specified speed (40,50, 60,...) km/h from a csv. file. I am a total novice in python and have not had much luck. I have tried to use different variations of for loops to extract the "Gällande Hastighet" (speed) column from the 2d list into a new list, but I am not allowed to use pandas. I have tried to use csv.reader and dictreader to append every 5th element into the new list but don't get any output. I have also tried using range. I have tried so many different alternatives and dont really know how to approach the question anymore. Any advice, resources, example code is appreciated.

The list looks like this:

[['MätplatsID', 'Gällande Hastighet', 'Hastighet', 'Datum', 'Tid'],
['14075010', '40', '55', '2021-09-11', '11:15:31'],
 ['14075010', '40', '54', '2021-09-11', '08:09:17'],
 ['14075010', '40', '53', '2021-09-11', '13:02:41'],
]

The end result should look like this: There are 69 measurements where the speed is 40 km/h

My rough code so far gives no output:

import csv

def number_of_cars(kamera_data):

with open('kameraData.csv', 'r', encoding = 'UTF-8') as csvfile:
    csv_reader =list(csv.reader (csvfile, delimiter = ';'))
   
    count = 0
    for i in range(len(csv_reader)):
        for j in range(len(csv_reader[i])):
            count  =data[i][j]
            print (count)

CodePudding user response:

IIUC, you want to transpose your list-of-lists and then count -

col_names, *data = lst

print(col_names)
# ['MätplatsID', 'Gällande Hastighet', 'Hastighet', 'Datum', 'Tid']

print(data)
# [['14075010', '40', '55', '2021-09-11', '11:15:31'],
#  ['14075010', '40', '54', '2021-09-11', '08:09:17'],
#  ['14075010', '40', '53', '2021-09-11', '13:02:41']]

transposed_data = zip(*data)
data_dict = dict()
for col_name, values in zip(col_names, transposed_data):
    data_dict[col_name] = values

Output

# print(data_dict)
{'MätplatsID': ('14075010', '14075010', '14075010'),
 'Gällande Hastighet': ('40', '40', '40'),
 'Hastighet': ('55', '54', '53'),
 'Datum': ('2021-09-11', '2021-09-11', '2021-09-11'),
 'Tid': ('11:15:31', '08:09:17', '13:02:41')}

Now you can count the number of entries for a particular speed -

print(len([speed for speed in data_dict['Gällande Hastighet'] if int(speed) == 40]))
# 3

CodePudding user response:

So, there is many ways to achieve what you need.

Using DictReader, you can read the csv file, iterate over the lines, and get the measured speed stored in another dict, where you can have multiple speeds.

After this, you just need to print each of the keys stored in this new dict.

Here is a example:

import csv

filename = 'carros.csv'
qty = 0
speeds = {}

with open(filename, 'r') as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        # used the method .get() to get the existing value, or 0, if is the first speed
        speeds[row['Gällande Hastighet']] = speeds.get(row['Gällande Hastighet'], 0)   1


for k in speeds.keys():
    print(f"There are {speeds[k]} measurements where the speed is {k} km/h.")

The result will be like this:

There are 3 measurements where the speed is 40 km/h.
There are 2 measurements where the speed is 41 km/h.
There are 1 measurements where the speed is 44 km/h.
  • Related