变量不会从python

时间:2015-09-06 21:53:22

标签: python variables

我已经为学校做了一个计算项目,在那里阅读了一个文本文件,花了最多的时间来锻炼每个强度。当它运行时,变量不会改变,它是仍然显示最高分是0,如果有人可以帮我告诉我哪里出错了会很好,

谢谢!

文本文档如下所示:

NeQua,High,Running,5,Swimming,40,Aerobics,40,Football,20,Tennis,10
ImKol,Moderate,Walking,40,Hiking,0,Cleaning,40,Skateboarding,30,Basketball,20
YoTri,Moderate,Walking,20,Hiking,30,Cleaning,40,Skateboarding,20,Basketball,40
RoDen,High,Running,20,Swimming,20,Aerobics,40,Football,30,Tennis,50

etc.
moderate_top_player = ""
high_top_player = ""
moderate_top_score = 0
high_top_score = 0


# open file, with will automatically close it for you
with open("text_documents/clientRecords.txt") as f:
    for line in f:
        ID,intensity,activity_1,time_1,activity_2,time_2,activity_3,time_3,activity_4,time_4,activity_5,time_5 = line.split(",")
        client_score = int(time_1) + int(time_2) + int(time_3) + int(time_4) + int(time_5)
        if intensity == "high" and  client_score > high_top_score:
            high_top_score = int(client_score)
            high_top_player = str(ID)

        elif intensity == "moderate" and  client_score > moderate_top_score:
            moderate_top_score = client_score
            moderate_top_player = ID

打印(moderate_top_player,"工作",moderate_top_score,"中等强度的分钟") 打印(high_top_player,"工作",high_top_score,"高强度分钟")

1 个答案:

答案 0 :(得分:3)

我冒昧地重命名了一些变量,并使用Python标准库中的csv模块读取文本文件,而不是手动分割基于逗号的行。

那就是说,问题很容易解决。您的数据集clientRecords.txt使用intensity的大写字符串(例如HighModerate),但在您的条件中,您将与小写字符串进行比较。 High == high会返回False,因此永远不会执行ifelif块的正文。

import csv

moderate_top_player = ""
high_top_player = ""
moderate_top_score = 0
high_top_score = 0

with open('text_documents/clientRecords.txt', 'rb') as f:
    reader = csv.reader(f)
    for row in reader:
        player_id, intensity, a1, t1, a2, t2, a3, t3, a4, t4, a5, t5 = row
        client_score = int(t1) + int(t2) + int(t3) + int(t4) + int(t5)
        intensity = intensity.lower()
        if intensity == 'high' and client_score > high_top_score:
            high_top_score = client_score
            high_top_player = player_id
        elif intensity == 'moderate' and client_score > moderate_top_score:
            moderate_top_score = client_score
            moderate_top_player = player_id

print moderate_top_player, moderate_top_score
print high_top_player, high_top_score

重要的一句话:

intensity = intensity.lower()

或者,您可以将intensity语句更改为针对if而不是High和{{1}进行测试,而不是将读入的high转换为小写。而不是Moderate。无论哪种方式都可以。