Reputation: 149
def cluster_guess_for_each_obs(self):
flat_cluster_guess = [self.argmax_list(cp) for cp in self.cluster_possibilities_for_observations()]
zero_cluster = [0.0 for i in self.clusters]
all_zero_clusters = [zero_cluster for p in range(len(flat_cluster_guess))]
for enum in enumerate(flat_cluster_guess):
all_zero_clusters[enum[0]][enum[1]] = 1.0
print all_zero_clusters
self.cluster_assignments = all_zero_cluster
return
Now the first line returns a list of 0s and 1s representing which cluster each data belongs to. I would like to convert this (ex.[0, 1, 0, 0, 1, 1, 1]) into a an array of arrays of length two which looks like this for above: [[1, 0], [0, 1], [1, 0], [1, 0], [0, 1], [0, 1], [0, 1]]. What I'm getting instead is after the first few enumeration it is all 1s.
Not sure what I'm doing wrong.
Upvotes: 0
Views: 60
Reputation: 78600
This line doesn't do what you think it does:
all_zero_clusters = [zero_cluster for p in range(len(flat_cluster_guess))]
It repeats the same list (not copies of the list- pointers to the same exact list) len(flat_cluster_guess)
times. That means that when you change one item in the list, you change all of them.
Instead, move the expression [0.0 for i in self.clusters]
into the list comprehension, like this:
all_zero_clusters = [[0.0 for i in self.clusters] for p in range(len(flat_cluster_guess))]
or
all_zero_clusters = [[0] * len(self.clusters) for p in range(len(flat_cluster_guess))]
Upvotes: 1
Reputation: 50185
flat = [0, 1, 0, 0, 1, 1, 1]
cluster = []
for pos in flat:
n = [0, 0]
n[pos] = 1
cluster.append(n)
print cluster
# [[1, 0], [0, 1], [1, 0], [1, 0], [0, 1], [0, 1], [0, 1]]
Upvotes: 1
Reputation: 6551
Okay, if I understand you correctly, you just need to implement a method that does this and call it once:
guess = [0, 1, 0, 0, 1, 1, 1]
def build_array(guess):
result = []
for i in range(len(guess)):
new_result.append([0,0])
for i in range(len(result)):
result[i][guess[i]] = 1
return result
Here I have chosen a solution that is more readable than 'Pythonic'. But hopefully this makes the basic logic you need to implement clear.
Upvotes: 1