Nov-02-2017, 04:00 PM
Your sample data:
Just as an example, don't use this code:
No need to make this strange nested iteration.
What you need to know:
csv_string='''type;latitude;longitude;speed T;37.547575;15.143184;0.963040 T;37.547569;15.143185;0.833400 T;37.547565;15.143186;0.351880 T;37.547561;15.143194;0.629680 T;37.547560;15.143205;1.129720 T;37.547561;15.143222;1.259360 T;37.547562;15.143236;1.129720'''The order of steps in your program:
- Read a line
- Convert data of the line
- Make decision if data is in boundaries
- If data is in boundaries -> yield data
Just as an example, don't use this code:
import csv from functools import partial import io def in_boundaries(lat, lon, lat_min, lat_max, lon_min, lon_max): return lat_min < lat < lat_max and lon_min < lon < lon_max # your boundaries boundaries = { 'lat_min': 37.547560, 'lat_max': 37.547570, 'lon_min': 15.143184, 'lon_max': 15.143186, } # functional approach, using keyword unpacking my_boundaries = partial(in_boundaries, **boundaries) csv_string = '''type;latitude;longitude;speed T;37.547575;15.143184;0.963040 T;37.547569;15.143185;0.833400 T;37.547565;15.143186;0.351880 T;37.547561;15.143194;0.629680 T;37.547560;15.143205;1.129720 T;37.547561;15.143222;1.259360 T;37.547562;15.143236;1.129720''' file_like_csv = io.StringIO(csv_string) reader = csv.reader(file_like_csv, delimiter=';') header = next(reader) #print(header) for row in reader: # the part where you split your row into columns try: type, latitude, longitude, speed = row except ValueError: print('Invalid column length:', row) continue try: # convert lat, lon to float latitude, longitude = map(float, [latitude, longitude]) except ValueError: print('Wrong value in:', row) continue # now decide if your data is in your defined boundary if my_boundaries(latitude, longitude): print(row) # here you should do something with your valid data else: # you don't need this. # this is just for control # print('Not in boundary:', row) passAt the end it's very easy. Make a function which decides if your data is in your boundaries and do something with it.
No need to make this strange nested iteration.
What you need to know:
- Exception handling
- argument unpacking
- keyword argument unpacking, if you're working with dicts. Not necessary.
- functions
- use of csv module
- knowledge of iterables, csv.reader is an iterator
- comparison with more than one value (min_val < val < max_val)
- logical operations: and, or, not
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
All humans together. We don't need politicians!