I have 3 lists; one of the names, one of data and one of the dates, I will print an example below (the actual dataset is much larger, first time I've asked on here)
List1 = [[Ref1,Ref2,Ref3],[Ref1,Ref2,Ref3,Ref4],[Ref2,Ref3]]
List2 = [[1,2,3],[1.1,2.1,3.1,4.1],[2.2,3.2]]
List3 = [2020,2019,2021]
I have managed to manipulate the data to have the order of the lists match with each other. What I need to do is to create graphs for each Refx with List 2 on the y-axis and List 3 as the x-axis.
I would like to make it in such a way to have separate lists for each of the Refx in date order, for example:
Ref1 = [1.1,1]
Ref2 = [2.1,2,2.2]
Ref3 = [3.1,3,3.2]
Ref4 = [4.1]
dates = [2019,2020,2021]
Then I could easily plot each Refx Some advice would be fantastic...
CodePudding user response:
The following codes will help you to solve your problem.
Ref1, Ref2, Ref3, Ref4 = [], [], [], []
Refs = [Ref1, Ref2, Ref3, Ref4]
List1 = [[Ref1, Ref2, Ref3], [Ref1, Ref2, Ref3, Ref4], [Ref2, Ref3]]
List2 = [[1, 2, 3], [1.1, 2.1, 3.1, 4.1], [2.2, 3.2]]
List3 = [2020, 2019, 2021]
for i in range(len(List1)):
for j in range(len(List1[i])):
List1[i][j].append((List3[i], List2[i][j]))
for r in Refs:
r.sort(key=lambda x: x[0])
Ref1 = [i[1] for i in Ref1]
Ref2 = [i[1] for i in Ref2]
Ref3 = [i[1] for i in Ref3]
Ref4 = [i[1] for i in Ref4]
print(Ref1)
print(Ref2)
print(Ref3)
print(Ref4)
Result:
[1.1, 1]
[2.1, 2, 2.2]
[3.1, 3, 3.2]
[4.1]
CodePudding user response:
This answer will restructure data into a dictionary, which is a bit different from what you are asking for in the question, but might also be helpful:
List1 = [["Ref1", "Ref2", "Ref3"], ["Ref1", "Ref2", "Ref3", "Ref4"], ["Ref2", "Ref3"]]
List2 = [[1, 2, 3], [1.1, 2.1, 3.1, 4.1], [2.2, 3.2]]
List3 = [2020, 2019, 2021]
# default dict will allow us accumulating values
from collections import defaultdict
d = defaultdict(list)
# this will iterate in the order sorted by List3 (first arg to zip)
for year, refs_keys, refs_vals in sorted(zip(List3, List1, List2)):
# this is to iterate over the nested lists
for ref_key, ref_val in zip(refs_keys, refs_vals):
d[ref_key].append(ref_val)
d["years"].append(year)
# convert to plain dict (optional)
d = dict(d)
print(d)