数组中的整数和浮点数不同

时间:2018-01-17 11:20:52

标签: python arrays python-3.x numpy user-interface

我有一个任务,我用数字,整数,浮点数和可能的字符串传递一个数组。然后我必须确定哪个元素包含在另一个具有纯整数的数组中,哪些不包含。必须打印那些未包含在具有整数的数组中,并且用户必须将该元素更改为包含在整数数组中的值。 虽然我遇到的问题是,如果给定数组中元素中的元素是浮点数,那么用户输入的输出也会变成浮点数(除非输入是带有整数的数组中的值。)如果给定数组中的元素是整数并且用户的输入是浮点数,也会出现同样的问题。然后浮点向下舍入为整数。任何人都可以提供我应该如何更改此代码的提示,以便脚本运行完美无瑕?

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.

0 个答案:

没有答案