I have a two-dimension array
[[ 1, 4, 4, 6, 6, 6, 8, 8, 8, 8, 9, 9, 9, 9, 9, 10, 11, 11, 11, 11, 11],
[ 0, 0, 1, 0, 1, 4, 0, 1, 4, 6, 0, 1, 4, 6, 8, 5, 0, 1, 4, 6, 8]]
I'm trying to parse it in such a manner that I end up with output that looks like this. Doesn't have to be dictionary but for visualizing I'm using something of the sort. Find every second coord for every unique value in the first array.
{
1: [0],
4: [0,1],
6: [0,1,4],
8: [0,1,4,6],
9: [0,1,4,6,8]
}
1 only had one second coord, of 0 4 had matching coords of 0 and 1 etc.
Any thoughts?
Thanks!
CodePudding user response:
Update
Using Python:
from itertools import groupby
lst = [[1, 4, 4, 6, 6, 6, 8, 8, 8, 8, 9, 9, 9, 9, 9, 10, 11, 11, 11, 11, 11],
[0, 0, 1, 0, 1, 4, 0, 1, 4, 6, 0, 1, 4, 6, 8, 5, 0, 1, 4, 6, 8]]
# Dict version
out = {k: [v[1] for v in l] for k, l in groupby(zip(*lst), key=lambda x: x[0])}
print(out)
# Output
{1: [0],
4: [0, 1],
6: [0, 1, 4],
8: [0, 1, 4, 6],
9: [0, 1, 4, 6, 8],
10: [5],
11: [0, 1, 4, 6, 8]}
# List version
out = [[v[1] for v in l] for k, l in groupby(zip(*lst), key=lambda x: x[0])]
Old answer
Using Pandas:
lst = [[1, 4, 4, 6, 6, 6, 8, 8, 8, 8, 9, 9, 9, 9, 9, 10, 11, 11, 11, 11, 11],
[0, 0, 1, 0, 1, 4, 0, 1, 4, 6, 0, 1, 4, 6, 8, 5, 0, 1, 4, 6, 8]]
df = pd.DataFrame(lst).T
# Dict version
out = df.groupby(0)[1].agg(list).to_dict()
print(out)
# Output
{1: [0],
4: [0, 1],
6: [0, 1, 4],
8: [0, 1, 4, 6],
9: [0, 1, 4, 6, 8],
10: [5],
11: [0, 1, 4, 6, 8]}
# List version
out = df.groupby(0)[1].agg(list).to_list()
CodePudding user response:
The following code seems to meet your output preferences.
Code:
val_list = [
[ 1, 4, 4, 6, 6, 6, 8, 8, 8, 8, 9, 9, 9, 9, 9, 10, 11, 11, 11, 11, 11],
[ 0, 0, 1, 0, 1, 4, 0, 1, 4, 6, 0, 1, 4, 6, 8, 5, 0, 1, 4, 6, 8]
]
val_dict = {}
for i, j in zip(val_list[0], val_list[1]):
if i in val_dict:
val_dict[i].append(j)
else:
val_dict[i] = [j]
print(val_dict)
Output:
{1: [0], 4: [0, 1], 6: [0, 1, 4], 8: [0, 1, 4, 6], 9: [0, 1, 4, 6, 8], 10: [5], 11: [0, 1, 4, 6, 8]}