简体   繁体   English

我的for循环中的错误在哪里?

[英]where is the mistake in my for loop?

Targets contains the target values and Observation contains the observations. Targets包含目标值, Observation值包含观察值。 I want my for-loop to count the number of different target values for each of the observation values and store them in the matrix obs_array where rows are the object values and the columns are the the target values. 我希望我的for循环为每个观察值计算不同目标值的数量,并将它们存储在矩阵obs_array ,其中行是对象值,列是目标值。 for the examples that I have provided it must return: 对于我提供的示例,它必须返回:

obs_array = [[3,2],[2 5]]

meaning that for zeros in the observation, there are 3 times 0 in the target values and 2 times 1 (the first list) and for the ones in the observations there are 2 times 0 and 5 times 1 (the second list) but the loop is not working correctly. 意味着对于观测值中的零,目标值中的3乘以0,对于目标值中的2乘以1(第一个列表),对于观察中的零而言,其目标值乘以2乘以0和5乘以1(第二个列表),但是循环无法正常工作。 Can you find the problem and explain it for me? 您能找到问题并为我解释吗? (I am new to Python) (我是Python新手)

Target = [1,1,1,0,0,1,0,1,1,0,0,1]
Observation = [1,0,1,0,1,1,0,1,1,1,0,0]

target_values = list(set(S))
observation_values = list(set(A))
obs_array = [[0 for x in range(len(observation_values))] for x in range(len(target_values))]

for k in range(len(observation_values)):
    for kk in range(len(Observation)):
        if observation_values[k] == Observation[kk]:
           for kkk in range(len(Target)):
               for kkkk in range(len(target_values)):
                   if Target[kkk] == target_values[kkkk]:
                       obs_array[k][kkkk]+=1

print(obs_array)

I know it's not really an answer to your question, but here's a fun solution to your problem (partly to help others understand what you're asking for, because the question is quite confusing): 我知道这并不是对您问题的真正答案,但这是对您的问题的有趣解决方案(部分是为了帮助其他人了解您的要求,因为问题非常令人困惑):

from collections import Counter

for (s, a), count in Counter(zip(S, A)).items():
    obs_array[s][a] = count

print obs_array  # [[3, 2], [2, 5]]

EDIT: I realise now that there's no need for such tricks. 编辑:我现在知道不需要这些技巧了。 This code will also work: 此代码也将起作用:

for i in range(len(S)):
    obs_array[S[i]][A[i]] += 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM