[Tutor] dynamically creating list
A.T.Hofkamp
a.t.hofkamp at tue.nl
Mon Mar 23 16:06:05 CET 2009
Bala subramanian wrote:
> 1) Now my question is, how to make this list creation dynamics, say if user
> enter number of clusters = 4, i would create four list. If the user enter 3,
> then i shd create three lists inside my program. How to do this dynamic
> creation of list depending on user input.
Use a list to collect everything, where each value represents data from a cluster.
Each value is a list of data points.
all = []
for n in range(num_clusters):
all.append([])
for point in data_points:
cluster = assign_cluster(point)
all[cluster].append(point)
This would give you something like
[ [ pointA1, pointA2, pointA3, ..., pointAn ],
[ pointB1, pointB2, pointB3, ..., pointBm ],
...
]
where 'pointAx' are points for the first cluster (number 0), 'pointBx' are
points for the second cluster (number 1), etc.
The list of points for cluster 'num' is then 'all[num]'.
A single point can be accessed as all[2][1] which gives you the second point
on the third cluster.
(or:
points = all[2]
print points[1]
)
Sincerely,
Albert
More information about the Tutor
mailing list