Tim
Tim

Reputation: 901

Split nested list based on unique value

I have got a list with vector points which I would like to split based on the second value of the nested list, the y position. So, points[0][1]. The example list contains two unique y heights: 920 and 940. But a list could have easily 10 unique y heights.

points = [(418, 920), (558, 920), (726, 920), (858, 920), (906, 920), (1042, 920), (418, 940), (558, 940), (734, 940), (865, 940), (899, 940), (1034, 940)]

# Desired result:
newPoints = [ [ [x,920], [x,920]  ], [ [x,940], [x,940] ] ] 

Upvotes: 1

Views: 79

Answers (2)

Maarten Fabré
Maarten Fabré

Reputation: 7058

This is where a collections .defaultdict comes in:

from collections import defaultdict
new_points = defaultdict(list)
for point in points:
    new_points[point[1]].append(point)
defaultdict(<class 'list'>, {
920: [(418, 920), (558, 920), (726, 920), (858, 920), (906, 920), (1042, 920)], 
940: [(418, 940), (558, 940), (734, 940), (865, 940), (899, 940), (1034, 940)]
})

If you need the lists, you can do new_points.values() or list(new_points.values())

[[(418, 920), (558, 920), (726, 920), (858, 920), (906, 920), (1042, 920)],
 [(418, 940), (558, 940), (734, 940), (865, 940), (899, 940), (1034, 940)]]

Upvotes: 1

Ollie
Ollie

Reputation: 1712

I created a dictionary of y-values to its list of x values, then iterated through the y-values, creating a sublist for each one, and iterated through the x-values, create a sublist for each of those.

points = [(418, 920), (558, 920), (726, 920), (858, 920), (906, 920), (1042, 920), (418, 940), (558, 940), (734, 940), (865, 940), (899, 940), (1034, 940)]

y_dict = dict()

for point in points:
    x = point[0]
    y = point[1]
    if y in y_dict.keys():
        #already found this y
        y_dict[y].append(x)
    else:
        #haven't found this y
        y_dict[y] = [x]

newPoints = []

for y in y_dict.keys():
    sublist = []
    for x in y_dict[y]:
        sublist.append([x, y])
    newPoints.append(sublist)

print(newPoints)

Then the result is:

[[[418, 920], [558, 920], [726, 920], [858, 920], [906, 920], [1042, 920]], [[418, 940], [558, 940], [734, 940], [865, 940], [899, 940], [1034, 940]]]

Upvotes: 0

Related Questions