I've a json file, whats include many values by different time, such as 05-01-2020 19:04:27. The time has also a specific value for example 05-01-2020 19:04:27. 3503.443.
How can I get a single value by a day, I dont want to print all values, just one by day. For example
- 05-01-2020 19:04:27, 2567.2
- 05-01-2020 19:44:51, 4333.54
- 05-01-2020 21:35:10, 4345.45
- 05-01-2020 23:04:49, 3503.443
from those I just need the first one.
I tried in Python range to loop a file and pick everyday, unfortunately the amount of value per day can be different. Someday there are 2 values, but someday even 22.
Summa summarum is there any function, what can get a first value of the day and skip the values of the same day and print it, then the next day's first value etc.? :)
CodePudding user response:
You could write each date to a dictionary so that there's only one value per date:
timestamps = [
"05-01-2020 19:04:27, 2567.2",
"05-01-2020 19:44:51, 4333.54",
"05-01-2020 21:35:10, 4345.45",
"05-01-2020 23:04:49, 3503.443",
"05-02-2020 00:04:49, 3503.443",
"05-02-2020 01:04:49, 3503.443",
]
value_by_day = {x.split()[0]: x for x in timestamps[::-1]}
print(list(value_by_day.values())[::-1])
This runs through it in opposite order so that the last value (per day) is the one that remains in the value_by_day
dictionary. Then print all of the values in the dictionary, but reverse the order again to get it back to chronological
Outputs:
['05-01-2020 19:04:27, 2567.2', '05-02-2020 00:04:49, 3503.443']
CodePudding user response:
How are the items in the list structured?
if every value is a single string : ("05-01-2020 23:04:49, 3503.443")
An ideal solution would be to iterate over the whole list, split the items and assign the result to different lists:
my_list = ["05-01-2020 23:04:49, 3503.443", "05-01-2020 23:04:49, 3503.443", "05-01-2020 23:04:49, 3503.443", "05-01-2020 23:04:49, 3503.443", "05-01-2020 23:04:49, 3503.443"]
datetime = []
values = []
for val in my_list:
split_val = val.split(" ")
datetime.append(f"{split_val[0]} {split_val[1][:-1]}")
values.append(split_val[2])
structured_list = list(zip(datetime, values))
def get_value(your_structured_list: list, datetime:str):
for val in your_structured_list:
if datetime == val[0]:
return val[1]
get_value(structured_list, '05-01-2020 23:04:49')