Python:如何在if语句中使用类型函数?

Python:如何在if语句中使用类型函数?,python,if-statement,types,Python,If Statement,Types,我正在编写一个从文件中加载数据列表的程序,我需要该程序来区分行中的数据是字符串还是整数。然而,在我编写的代码中,程序没有区分数字和字符串 我拥有的数据列表示例如下: HAJOS ALFRED 1896 1 我的代码: def medalsYear(): times = 1 totalGold = 0 totalSilver = 0 totalBronze = 0 while times <= 5: alpha = fob.readline() #reads f

我正在编写一个从文件中加载数据列表的程序,我需要该程序来区分行中的数据是字符串还是整数。然而,在我编写的代码中,程序没有区分数字和字符串

我拥有的数据列表示例如下:

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")
从文件中读取的数据总是字符串。您需要尝试转换这些行,而不是测试它们的类型:

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()
将在无法将
alpha
解释为整数时引发
ValueError
。如果引发异常,则会导致Python跳转到
除ValueError:
块,而不是执行
try:
套件的其余部分。

您可以制作一个dict,其中键是
“1”、“2”和“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")
如果要在通过循环赢得奖牌时打印:

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")
打开(填充)为f:
次数=1
奖牌名称={“1”:[0,“金”],“2”:[0”,“银”],“3”:[0”,“铜”}

当输出显示时间时,所有值实际上都是字符串。当您从这样的文件中读取数据时,您总是在读取字符串。如果你想把它们转换成整数,你需要自己去做。提示:
int(alpha)
alpha
转换成整数,或者如果不能的话抛出一个
ValueError
如果alpha.isdigit()
也会比我(现在已删除)的答案好很多。。。阅读问题的方式…:P+1@JoranBeasley:将问题编辑成某种形状有助于理解。:-)我只是试着在我的代码中实现它,它在很大程度上起了作用。不过,唯一的问题是,如果使用它,无论如何都不会更新获得的奖牌总数。但是,它确实正确地将字符串转换为整数。编辑:没关系,我只是有个语法错误。
(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")