2016-02-21 99 views
0

我想比较项目值。如果它们相等,我想打印“真”,否则我想打印“假”。我的代码写入结果。列表值比较 - For循环迭代

我的结果"prediction_list"中,我比较2 lists(test_labels and my_labels值)的大小应该是260,因为我原来lists(test_labels and my_labels)有260大小然而,我prediction_list有因为对循环迭代的67600大小。我应该如何改正它?

prediction = [] 

for i in test_labels: 
    for item in my_labels: 
     if item == int(i): 
      prediction.append("true") 
     else: 
      prediction.append("false") 

print prediction 

样品的输入和输出:

NB分类标签测试设置:[1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]

test_labels:['0\n', '0\n', '0\n', '0\n', '0\n', '0\n', '0\n', '0\n', '0\n', '0\n', '0\n', '0\n', '0\n', '0\n', '0\n', '0\n', '0\n', '0\n', '0\n', '0\n', '0\n', '0\n', '0\n', '0\n', '0\n', '0\n', '0\n', '0\n', '0\n', '0\n', '0\n', '0\n', '0\n']

预测:['false', 'false', 'false', 'true', 'false', 'false', 'false', 'true', 'false', 'false', 'false', 'false', 'false', 'false', 'false', 'false', 'false', 'false', 'false', 'false', 'false', 'false', 'false', 'false', 'false'...]

回答

1

我同意@MarkPython,但有一个稍微清晰的语法。

prediction = [] 

for i in range(len(test_labels)): 
    if test_labels[i] == my_labels[i]: 
     prediction.append("true") 
    else: 
     prediction.append("false") 
+0

感谢您的简化! – MarkyPython

+0

不客气!默认情况下Python的范围从零开始,除非另有定义。 – Trey50Daniel

3

而不是通过列表循环的尝试循环通过一个范围,并使用数字来检查e中每个项目的值在该索引处列出。下面是代码:

prediction = [] 

for i in range(0, len(test_labels)): 
    if my_labels[i] == test_labels[i]: 
     prediction.append("true") 
    else: 
     prediction.append("false") 

print prediction 
+0

谢谢! @MarkyPython – serenade

+0

@serenade:你也可以使用list comprehension:'prediction = [“true”if my_labels [i] == test_labels [i] else“false”for range in(len(test_labels))' – zondo

+0

我意识到你可以做到这一点,但我更喜欢长版本的可读性。 – MarkyPython

3

如果你确定test_labels和my_labels大小相同,你可以很容易地用“压缩”功能:

prediction = [] 

for x, y in zip(test_labels, my_labels): 
    if x == y: 
     prediction.append("true") 
    else: 
     prediction.append("false") 

print(prediction)