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
现在第一行返回0和1的列表,表示每个数据所属的集群。我想将此(例如[0,1,0,0,1,1,1])转换为长度为2的数组数组,如上所示:[[1,0],[0 ,1],[1,0],[1,0],[0,1],[0,1],[0,1]]。我得到的是在前几次枚举之后,它全部为1。
不确定我做错了什么。
答案 0 :(得分:1)
好的,如果我理解正确,你只需要实现一个方法来执行此操作并调用一次:
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
在这里,我选择了比'Pythonic'更具可读性的解决方案。但希望这会使您需要实现清晰的基本逻辑。
答案 1 :(得分:1)
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]]
答案 2 :(得分:1)
此行不符合您的预期:
all_zero_clusters = [zero_cluster for p in range(len(flat_cluster_guess))]
它重复相同列表(不是指向同一列表的列表指针的副本)len(flat_cluster_guess)
次。这意味着当您更改列表中的一个项目时,您将更改所有项目。
相反,将表达式[0.0 for i in self.clusters]
移动到列表推导中,如下所示:
all_zero_clusters = [[0.0 for i in self.clusters] for p in range(len(flat_cluster_guess))]
或
all_zero_clusters = [[0] * len(self.clusters) for p in range(len(flat_cluster_guess))]