Python—执行时间比平常长
我决定编写一个简单的python代码,以便轻松地获得以Python—执行时间比平常长,python,python-2.7,Python,Python 2.7,我决定编写一个简单的python代码,以便轻松地获得以m/d/yyyy格式输入日期的日期。我用excel将日期上传到一个.txt文件中。新的.txt文件包含从2018年1月1日起到2022年12月31日止的日期,相应的日期用逗号分隔 该程序运行良好,但几乎需要一分钟才能得到结果。如何更改代码以提高执行时间 这是我的密码: def getList(): name = 'Calendar2018.txt' dates = open(name, 'r') newList = []
m/d/yyyy
格式输入日期的日期。我用excel将日期上传到一个.txt文件中。新的.txt文件包含从2018年1月1日起到2022年12月31日止的日期,相应的日期用逗号分隔
该程序运行良好,但几乎需要一分钟才能得到结果。如何更改代码以提高执行时间
这是我的密码:
def getList():
name = 'Calendar2018.txt'
dates = open(name, 'r')
newList = []
for line in dates:
newList.append(line)
for i in range(0,len(newList)):
newList[i] = newList[i].split(',')
for i in range (0,len(newList)):
for x in range (0,len(newList[i])):
newList[i][x] = (str(newList[i][x]).translate(None,'"')).strip()
return newList
userInp = raw_input("Enter a date: ")
for i in range(0,len(getList())):
if (getList()[i][0]) == userInp:
print userInp + " falls on " + getList()[i][1] + "."
问题是您一次又一次地调用
getList
。相反,只需调用一次并将结果存储在列表中:
all_the_dates = getList()
userInp = raw_input("Enter a date: ")
for i in range(0,len(all_the_dates)):
if (all_the_dates[i][0]) == userInp:
print userInp + " falls on " + all_the_dates[i][1] + "."
或更短,直接迭代列表,而不是使用索引的范围
:
for date, weekday in all_the_dates:
if date == userInp:
print userInp + " falls on " + weekday + "."
话虽如此,您根本不需要那个“日历”文件。只需使用Python的API,就可以获得工作日
>>> import datetime
>>> userinp = "2/1/2018"
>>> m,d,y = map(int, userinp.split("/"))
>>> datetime.date(y, m, d).strftime("%A")
'Thursday'
首先,找出你的代码中哪一部分实际上是慢的。这很有道理。谢谢您!