Reputation: 354
I receive constant data, for ease of life I get both data values that I receive and put them into each into a different array, the idea of this is so that I can link a value of Variable2 to a value of Variable1. Now, Variable1 will always be a value between 0 and 7, which I want to use this value to index the other array containing all values from variable2, data is polled serially inside a for loop, so I get data for both variables constantly. an example of data I get:
Variable1: 6 Variable2: 1499.6
Variable1: 6 Variable2: 1186.5
Variable1: 6 Variable2: 570.4
Variable1: 1 Variable2: 405.9
Variable1: 1 Variable2: 754.0
Variable1: 1 Variable2: 197.2
Variable1: 1 Variable2: 726.0
Variable1: 1 Variable2: 959.1
Variable1: 1 Variable2: 709.6
An example of two arrays of data for variable1 and variable 2 is below:
Variable2 ={ [1499.6, 1186.5, 570.4, 405.9, 754.0, 197.2, 726.0, 959.1, 709.6]}
Variable1 ={ [[6], [6], [6], [1], [1], [1], [1], [1], [1]]}
So my question is how would I grab these two arrays and make it so for example if I where to do print(VariableArray[6][2]) results in it printing : 570.4 which is the 3rd variable2 corresponding to Variable1 = 6
Upvotes: 3
Views: 68
Reputation: 21975
I'd go with a dictionary of lists:
{
6: [1499.6, 1186.5, 570.4],
1: [405.9, 754.0, 197.2, 726.0, 959.1, 709.6]
}
As an example in the Python REPL:
>>> d = {6: [1499.6, 1186.5, 570.4], 1: [405.9, 754.0, 197.2, 726.0, 959.1, 709.6]}
>>> d[6][2]
570.4
The idea is:
Keep a key for your 0
to 7
values (initially Variable1
) and for each of those, store a list of values where you push the new data.
You could initialize this dictionary like so:
d = {
0: [],
1: [],
2: [],
3: [],
4: [],
5: [],
6: [],
7: [],
}
Or you could use a defaultdict, but first, make sure you understand lists and dictionaries.
In order to append data to a list you'd do (assuming 42.0
is your new value and the dictionary already contains the data you posted in the question):
d[6].append(42.0)
Which yields:
{6: [1499.6, 1186.5, 570.4, 42.0], 1: [405.9, 754.0, 197.2, 726.0, 959.1, 709.6]}
Or more generally: d[Variable1].append(Variable2)
.
Note: make sure your list will not grow indefinitely.
Please read the general theory and usage on dictionaries and lists in Python here (minimal reading for better understanding):
Upvotes: 4