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

2024-04-29 16:52:26 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我有一个数据列表示例:

HAJOS
ALFRED
1896
1

我的代码:

^{pr2}$

我的问题是,当程序读取一个包含整数的行时,它无法正确确定该行是否包含整数,并从中遍历相应的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

Tags: 文件数据字符串代码程序列表stringis
2条回答

你可以做一个dict,其中的键是"1","2" and "3"来对应金、银、青铜和usedict.获取. 在

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")

哪些输出:

^{pr2}$

如果您想在通过循环获得奖牌时打印:

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")

从文件中读取的数据始终是字符串。您需要尝试转换这些行,而不是测试它们的类型:

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')

alpha不能解释为整数时,int()将引发ValueError。如果引发异常,则会导致Python跳转到except ValueError:块,而不是执行try:套件的其余部分。在

相关问题 更多 >