I have question about the usage of list comprehension in reading files as a csv or json file. In this first code I am using the normal long way to take a value of a row and append it in the end to an empty list. This works fine with no problem at all as expected:
with open("file.csv") as W_F:
reader = csv.reader(W_F)
header = next(reader)
brightness,lons,lats=[], [], []
for row in reader:
bright=float(row[2])
brightness.append(bright)
lons.append(float(row[0]))
lats.append(float(row[1]))
In this code I tried making my code smaller by using a list comprehension, but here I am getting a problem. I am only getting the value of the first list brightness = [float(row[2]) for row in reader]
. The other lists are getting printed as an empty list (lon = [float(rows[1])for rows in reader]
and lat = [float(rows[1])for rows in reader]
).
with open("file.csv") as W_F:
reader = csv.reader(W_F)
header = next(reader)
brightness = [float(row[2]) for row in reader]
lon = [float(rows[0])for rows in reader]
lat = [float(rows[1])for rows in reader]
Here I am using a list comprehension while reading a json file. I am getting all the values without a problem:
with open("file.json")as f:
all_eq_data = json.load(f)
all_eq_dicts = all_eq_data['features']
mag = [dicts["properties"]["mag"] for dicts in all_eq_dicts]
lang = [dicts["geometry"]["coordinates"][0] for dicts in all_eq_dicts]
lat = [dicts["geometry"]["coordinates"][1] for dicts in all_eq_dicts]
Can someone please explain to me why the list comprehension in the second code doesn't work properly? Why in the second code it's only storing values in the first list but not the others? Why it's working in the 3rd code but not in the second? What is the difference between the first code and the second if I am doing something wrong (Note: first and second code are using the same file).