数组中整数和浮点之间的差异

2024-09-27 23:28:40 发布

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

我有一个任务,在那里我被交给了一个数组,里面有数字,整数,浮点数,可能还有字符串。然后我必须确定哪些元素包含在另一个纯整数数组中,哪些元素不包含。必须打印不包含在整数数组中的元素,并且用户必须将元素更改为包含在整数数组中的值。 虽然我有一个问题,如果给定数组中的元素是一个浮点,那么用户输入的输出也会变成一个浮点(除非输入是一个整数数组中的值)。如果给定数组中的元素是一个整数,而用户的输入是一个浮点,同样的问题也会发生。然后浮点向下舍入为整数。有没有人能告诉我应该如何修改这段代码,让脚本运行得完美无瑕?你知道吗

grades = np.array([-3,-10.5,0,7,4,8,4,7,10,5])
SevenGradeScale = np.array([-3, 0, 2, 4, 7, 10, 12])
SevenGradeScale = SevenGradeScale.astype(int)
for i in range(np.size(grades)):
    if grades[i] not in SevenGradeScale:
        while True:  
            if grades[i] in SevenGradeScale:
                grades = grades.astype(int)
                print("The grade has been changed to {:d}. ".format(grades[i]))
                break
            elif type(grades[i]) is np.float64:
                print("\n{:.1f} is not a valid grade. The grade must be an integer.".format(grades[i]))
            elif type(grades[i]) is np.int32:
                print("\n{:d} is not within the seven grade scale.".format(grades[i]))
            elif type(grades[i]) is str:
                type("\n{:s} is not a valid grade.".format(grades[i]))
            try:
                grades[i] = float(input("Insert new grade: "))
            except ValueError:
                pass

您可能会对“float(input())”进行注释,但这在某种程度上帮助了我的脚本。虽然我不知道是否还有其他的可能性。你知道吗

当运行代码并键入随机输入时,我得到以下结果

-

10.5 is not a valid grade. The grade must be an integer.

Insert new grade: 10.7

10.7 is not a valid grade. The grade must be an integer.

Insert new grade: 10
The grade has been changed to 10. 

8 is not within the seven grade scale.

Insert new grade: 7.5
The grade has been changed to 7. 

5 is not within the seven grade scale.

Insert new grade: 5.5

5 is not within the seven grade scale.

Insert new grade: string

5 is not within the seven grade scale.

Insert new grade: 0
The grade has been changed to 0.

Tags: the元素newisnpnot整数数组

热门问题