我正在编写一个程序来加载文件中的数据列表,我需要程序来区分行中的数据是字符串还是整数。但是在我完成的代码中,程序并没有区分数字和字符串。
我拥有的数据列表示例:
HAJOS
ALFRED
1896
1
我的代码:
def medalsYear():
times = 1
totalGold = 0
totalSilver = 0
totalBronze = 0
while times <= 5:
alpha = fob.readline() #reads file line by line#
print(alpha)
times = times + 1
if type(alpha) == int:
if alpha == 1:
totalGold = totalGold + 1
print("gold medal won")
elif alpha == 2:
totalSilver = totalSilver + 1
print("silver medal won")
elif alpha == 3:
totalBronze = totalBronze + 1
print("bronze medal won")
else:
pass
else:
print('is a string')
print(totalGold, "Gold medals won")
print(totalSilver, "Silver medals won")
print(totalBronze, "Bronze medals won")
我的问题是当程序读取一个具有整数的行时,如果该行包含一个整数并且从那里运行相应的if语句,它就不能正确地确定。目前我的输出看起来像这样。
HAJOS
is a string
ALFRED
is a string
1896
is a string
1
is a string
is a string
0 Gold medals won
0 Silver medals won
0 Bronze medals won
done
答案 0 :(得分:2)
从文件读取的数据始终将成为字符串。您需要尝试转换这些行,而不是测试它们的类型:
try:
alpha = int(alpha)
if alpha == 1:
totalGold = totalGold + 1
print("gold medal won")
elif alpha == 2:
totalSilver = totalSilver + 1
print("silver medal won")
elif alpha == 3:
totalBronze = totalBronze + 1
print("bronze medal won")
except ValueError:
print('is a string')
当int()
无法解释为整数时, ValueError
会引发alpha
。如果引发异常,则会导致Python跳转到except ValueError:
块而不是执行try:
套件的其余部分。
答案 1 :(得分:0)
你可以制作一个dict,其中键为"1","2" and "3"
,对应金,银,铜,并使用dict.get。
with open(infile) as f:
times = 1
medal_dict = {"1": 0, "2": 0, "3": 0}
while times <= 5:
alpha = f.readline().rstrip() #reads file line by line#
times += 1
if medal_dict.get(alpha) is not None:
medal_dict[alpha] += 1
else:
print("is a string")
print(medal_dict["1"], "Gold medals won")
print(medal_dict["2"], "Silver medals won")
print(medal_dict["3"], "Bronze medals won")
哪个输出:
(1, 'Gold medals won')
(0, 'Silver medals won')
(0, 'Bronze medals won')
如果你想通过循环赢得奖牌时打印:
with open(infile) as f:
times = 1
medal_dict = {"1": [0,"gold"], "2": [0,"silver"], "3": [0,"bronze"]}
while times <= 5:
alpha = f.readline().rstrip() #reads file line by line#
print(alpha)
times += 1#
check = medal_dict.get(alpha)
if check is not None:
medal_dict[alpha][0] += 1
print("{} medal won".format(check[1]))
else:
print("is a string")
print(medal_dict["1"][0], "Gold medals won")
print(medal_dict["2"][0], "Silver medals won")
print(medal_dict["3"][0], "Bronze medals won")