循环执行不正确

时间:2019-10-25 21:14:35

标签: python python-3.x loops if-statement syntax

我正在尝试创建一个计算列表中元素长度的函数,然后对它们运行if / elif循环:

k_nearest_samples_class = training_data[sorted_indices[:k]][:, -1]
# print(k_nearest_samples_class)
# counting number of occurrences of either 0's or 1's with below 2 lines
class_0_count = len(k_nearest_samples_class[k_nearest_samples_class == 0])
class_1_count = len(k_nearest_samples_class[k_nearest_samples_class == 1])
class_2_count = len(k_nearest_samples_class[k_nearest_samples_class == 2])

# Combining > & = sign so even in tie-up cases the instance will be classified to malignant - assumed it
# would be okay in order to reduce false positives
if class_0_count >= class_1_count and class_2_count:
    print("0", class_0_count)
    return 0
elif class_1_count >= class_0_count and class_2_count:
    print("1", class_1_count)
    return 1
else:
    print("2", class_2_count)
    return 2

一一对应地输入:

[0.0]
[1.0]
[2.0]

当前,我的if循环无法正常工作。

2 个答案:

答案 0 :(得分:1)

此行:

if class_0_count >= class_1_count and class_2_count:

等效于:

if class_0_count >= class_1_count and class_2_count > 0:

您需要将其更改为:

if class_0_count >= class_1_count and class_0_count >= class_2_count:

或者您可以将两者的最大值进行比较:

if class_0_count >= max(class_1_count, class_2_count):

答案 1 :(得分:0)

扩展@MoeA的上述答案:

执行此测试的另一种Python方法是使用all()函数,例如:

if all([class_0_count >= class_1_count, class_0_count >= class_2_count]):
    ...