Python:将索引值与List值匹配

时间:2016-02-08 08:22:51

标签: python list tuples list-comprehension

输出包含(有些)相应元组列表的分组元素索引值的列表列表,如何将它们组合成分组元组列表?

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]]

这些是样本值/组。 我问的问题的例子:

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

我已经尝试过列表推导和拉链,但是当涉及到在群集中获取[i]的值时,它会让人感到困惑。

1 个答案:

答案 0 :(得分:5)

我认为你想要的是两级列表理解:

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