我正在尝试编写一个函数,通过使用嵌套列表(深度为 2)来管理每天的待办事项列表。我正在处理一个定义了任务列表的文件。一项任务的格式如下所示:
'email', 9, 15, 2, 0, 70, 'Answer all the emails received today.'
每个任务的格式是:
任务名称。
任务日期:月(1 到 12 之间的整数)。
任务日期:天(1 到 31 之间的整数)。
任务的开始时间:小时(采用 24 小时格式,因此是 1 到 24 之间的整数),例如,对于上午 9:15,此条目为 9。如果开始时间为 11:下午 45 点,本条目为 23 点。
任务的开始时间:分钟(0 到 59 之间的整数)。
任务时长(分钟):2 小时 20 分钟的任务时长为 140 分钟。
任务的一般描述。
我的函数必须采用 [10,1] 形式的日期(表示 10 月 1 日),并打印出当天根据开始时间排序的所有任务。它应该是这样的:
These are your tasks for Oct. 1
Task Name: coffee
Start time: 8:25 AM
End time: 8:30 AM
Description: making coffee
Task Name: lunch
Start time: 12:00 PM
End time: 12:30 PM
Description: Lunch time
我该如何处理?我已经为月份和日期定义了函数,但我试图首先编写一个函数来比较日期,然后根据哪个先出现来比较任务。如果你能帮忙,请告诉我。
def print_tasks(tasks, date_list):
"""Print all the tasks for the given date from the given list of tasks.
Arguments:
tasks--A nested list, where each inner list represents the information on
a single task.
date_list--a list of two integers representing the month and day for which
the tasks should be printed. For example, [10, 1] represents Oct. 10th
(month=10, day=1).
"""
for task in tasks:
if task[1] == date[0] and task[2] == date[1]:
if task[3] > 12:
start_time = ' PM'
task[3] -= 12
else:
start_time = ' AM'
if task[3] > 12:
end_time = ' PM'
task[3] -= 12
else: end_time = ' AM'
print 'Task Name:', task[0]
print 'Start time:', task[3], ':', task[4]
print 'End time:'
# Please complete me. Define several other functions and call them here
# to complete me.
def main():
"""The main function (please don't remove). However, please feel free to
change the second argument passed to print_tasks here to test your
print_tasks function with different inputs.
"""
# The variable tasks is the nested list storing the tasks.
return None
更新代码:
tasks = [
['email', 9, 15, 2, 0, 70, 'Answer all the emails received today.'],
['coffee', 10, 1, 8, 25, 5, 'making coffee'],
['meeting', 3, 5, 12, 0, 80, 'group meeting'],
['sleep', 12, 8, 3, 20, 280, 'getting some sleep'],
['meeting', 10, 1, 17, 0, 60, 'group meeting'],
['laundry', 3, 5, 21, 0, 40, 'do laundry'],
['office hours', 10, 1, 14, 0, 120, 'Office hours for Biology II'],
['class', 3, 5, 15, 0, 50, 'CS1 class'],
['laundry', 11, 5, 13, 0, 80, 'Laundry'],
['laundry', 10, 1, 19, 45, 40, 'Do laundry'],
['lunch', 10, 1, 12, 0, 30, 'Lunch time'],
['class', 3, 5, 10, 0, 50, 'Philosophy class'],
['break', 2, 1, 11, 0, 45, 'quick break before lunch.'],
['exam prep', 11, 13, 10, 0, 600, 'study for the exam.']]
def make_date_from_tasks(tasks):
dates = []
for task in tasks:
dates.append([task[1], task[2]])
return dates
dates = make_date_from_tasks(tasks)
def task_month(number):
if number == 1:
return 'January'
if number == 2:
return 'February'
elif number == 3:
return 'March'
elif number == 4:
return 'April'
elif number == 5:
return 'May'
elif number == 6:
return 'June'
elif number == 7:
return 'July'
elif number == 8:
return 'August'
elif number == 9:
return 'September'
elif number == 10:
return 'October'
elif number == 11:
return 'November'
else:
return 'December'
def print_tasks(tasks, date_list):
for task in tasks:
if task[1] == date[0] and task[2] == date[1]:
if task[3] > 12:
start_time = ' PM'
task[3] -= 12
else:
start_time = ' AM'
if task[3] > 12:
end_time = ' PM'
task[3] -= 12
else:
end_time = ' AM'
print statements (I’m confused as to what to write here to format it correctly)
for date in dates:
print_tasks(tasks, date)
最佳答案
我举了一个小例子来说明我将如何处理这个...
假设我们有一个包含数据的数组(可以存储在外部文件或数据库中):
jsonarray = [
{
'name':'email',
'datetime':"2017-09-15 04:00:00",
'length':70,
'description':'Answer all the emails received today.'
},
{
'name':'email',
'datetime':"2017-09-16 08:00:00",
'length':70,
'description':'Answer all the emails received today.'
},
{
'name':'email',
'datetime':"2017-09-15 03:00:00",
'length':70,
'description':'Answer all the emails received today.'
}
]
然后我们可以读取数据并创建一个函数来返回我们可以根据日期打印的格式化字符串:
import datetime
import pandas as pd
df = pd.DataFrame(jsonarray)
df.datetime = pd.to_datetime(df.datetime)
printformat = """
Task Name: {}
Start time: {}
End time: {}
Description: {}
"""
def print_tasks(maskby):
mask = df[df['datetime'].dt.date.astype(str) == maskby].sort_values(by='datetime')
s = ['These are your tasks for {}:\n'.format(maskby)]
for ind,row in mask.iterrows():
name = row["name"]
stime = row["datetime"].strftime("%H:%M")
etime = (row["datetime"] + datetime.timedelta(minutes=row["length"])).strftime("%H:%M")
desc = row["description"]
s.append(printformat.format(name,stime,etime,desc))
return ''.join(s)
print(print_tasks("2017-09-15"))
输出:
These are your tasks for 2017-09-15:
Task Name: email
Start time: 03:00
End time: 04:10
Description: Answer all the emails received today.
Task Name: email
Start time: 04:00
End time: 05:10
Description: Answer all the emails received today.
好的,如果您有兴趣并看到您的示例数据,那么这个列表就是您想要学习的东西:
日期时间库:
- datetime.strptime() - 字符串 --> 日期时间
- datetime.strftime() - 日期时间 --> 字符串
- datetime.timedelta() - 时间增量
字符串格式:
- str.format() - 打印字符串的有效方法
- ''.join() - 将列表转换为字符串的有效方法
此外,要理解我写的代码..看看:
- json(一种以人类可读字符串形式存储信息的方法)
- 字典(以键值对形式存储数据)
- pandas(python 处理表数据最有效的库)
- 带有可选键参数的 sorted() 函数对数据进行排序
如果你想继续,我会给你一些片段:
array = [
['email', 9, 15, 2, 10, 70, 'Answer all the emails received today.'],
['email', 9, 15, 2, 0, 70, 'Answer all the emails received today.'],
['email', 9, 15, 3, 0, 70, 'Answer all the emails received today.']
]
printformat = """
Task Name: {}
Start time: {}
End time: {}
Description: {}
"""
date = [9,15]
s = ['These are your tasks for {}:\n'.format(date)]
for item in sorted(array,key=lambda x:(x[3],x[4])):
if item[1:3] == date:
s.append(printformat.format(item[0],item[1],item[2],item[3]))
print(''.join(s))
返回:
These are your tasks for [9, 15]:
Task Name: email
Start time: 9
End time: 15
Description: 2
Task Name: email
Start time: 9
End time: 15
Description: 2
Task Name: email
Start time: 9
End time: 15
Description: 3
关于python - 待办事项列表 Python 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46983310/