使用Python中的lists和if语句将字符串(用户输入)转换为整数

时间:2017-11-05 17:07:00

标签: python python-3.x

最近我有一个学校项目,其中我需要将用户输入作为1-12之间的整数(代表一年中的几个月)和用户的年龄,并做一个数学等式来产生一个数字这将吐出用户的年龄和出生月份(是的,我知道这是多余的,但我必须做数学方程而不是吐出用户输入)。我是一个想要100%试图让它成为用户可以用字符串输入月份的孩子,例如(Jan = 1)使用list和if语句。如果语句没有改变birthNum变量,那么下面的代码就不会像用户输入内容那样工作。所以请帮助我,因为我已经尝试了几乎所有的东西而且没有任何作用,但我觉得好像我如此接近它的工作。

以下是将用户输入(字符串)转换为整数的代码:

birthNum = 0

listOfMonths = ["January", "Jan", "january", "jan", "1", "Febuary", "Feb", "febuary", "feb", "2", "March", "Mar", "march", "mar", "3", "April", "Apr", "april", "apr", "4", "May", "may", "5", "June", "Jun", "june", "jun", "6", "July", "Jul", "july", "jul", "7", "August", "Aug", "august", "aug", "8", "September", "Sept", "september", "sept", "9", "October", "Oct", "october", "oct", "10", "November", "Nov", "november", "nov", "11", "December", "Dec", "december", "dec", "12"]

janList = ["January", "Jan", "january", "jan", "1"]

febList = ["Febuary", "Feb", "febuary", "feb", "2"]

marList = ["March", "Mar", "march", "mar", "3"]

aprList = ["April", "Apr", "april", "apr", "4"]

mayList = ["May", "may", "5"]

junList = ["June", "Jun", "june", "jun", "6"]

julList = ["Jul", "july", "jul", "7"]

augList = ["September", "Sept", "september", "sept", "9"]

septList = ["September", "Sept", "september", "sept", "9"]

octList = ["October", "Oct", "october", "oct", "10"]

novList = ["November", "Nov", "november", "nov", "11"]

decList = ["December", "Dec", "december", "dec", "12"]

(birthMonthInput) = input("Please put in your birth month: ")


if (birthMonthInput == (janList)):
    birthNum = int(1)

if (birthMonthInput == (febList)):
    birthNum = int(2)

if (birthMonthInput == (marList)):
    birthNum = int(3)

if (birthMonthInput == (aprList)):
    birthNum = int(4)

if (birthMonthInput == (mayList)):
    birthNum = int(5)

if (birthMonthInput == (junList)):
    birthNum = int(6)

if (birthMonthInput == (julList)):
    birthNum = int(7)

if (birthMonthInput == (augList)):
    birthNum = int(8)

if (birthMonthInput == (septList)):
    birthNum = int(9)

if (birthMonthInput == (octList)):
    birthNum = int(10)

if (birthMonthInput == (novList)):
    birthNum = int(11)

if (birthMonthInput == (decList)):
    birthNum = int(12)

print (birthNum)

2 个答案:

答案 0 :(得分:1)

使用列表是非常不可靠的。您的解决方案需要大约5 * 12次查找才能获得与String相关联的值。

可以在O(1)中执行此用例的更快速的数据结构是一个字典。 尝试格式化您的代码:

dic = {
   "Jan": 1,
   "January": 1,
   "Feb": 2 # and so on
}

然后您可以通过以下方式获得解决方案:

birthNum = dict[birthMonthInput]

阅读python data structures以获得良好的概述。字典是第5.5节

答案 1 :(得分:1)

您的条件是检查字符串是否符合列表。您正在寻找的是in关键字 - 即

if birthMonthInput in augList:

那就是说,你的代码中还有很多其他问题。