DomRow February 2016

Python: Matching Index values to List values

Having an output of a list of lists containing index values of grouped elements for a (somewhat) corresponding list of tuples, how do I combine them into a list of grouped tuples?

data=[(1, 1), (1.5, 2), (3, 4), (5, 7), (3.5, 5), (4.5, 5), (3.5, 4.5)]
clusters=[[0], [], [4], [1, 2, 3, 5, 6]]

These are sample values/groups. Example of what I'm asking about:

coordinates= [[(1,1)], [], [(3.5,5)], [(1.5,2),(3,4),(5,7),(4.5,5),(3.5,4.5)]]

I've tried list comprehensions and zips but when it comes to getting the value of [i] in clusters it gets confusing.

Answers


Blckknght February 2016

I think a two-level list comprehension is what you want:

coordinates = [[data[index] for index in cluster] for cluster in clusters]

Post Status

Asked in February 2016
Viewed 2,483 times
Voted 7
Answered 1 times

Search




Leave an answer