我有一个任务列表,我试图选择具有给定ID的所有任务。Python - 为什么这个列表理解返回一个空列表?
# temp global tasks list
tasks = [
{
'id': 1,
'title': u'Buy groceries',
'description': u'Milk, Cheese, Pizza, Fruit, Tylenol',
'done': False
},
{
'id': 2,
'title': u'Learn Python',
'description': u'Need to find a good Python tutorial on the web',
'done': False
}
]
# here I try to select some tasks. 'request.args.get('id')' is 2 in my test
selectedTasks = tasks
if 'id' in request.args:
selectedTasks = [task for task in selectedTasks if task['id'] == request.args.get('id')]
如果我运行这个,selectedTasks
是空的。但我不明白为什么。
我想打印一些值:
# just before the list comprehension
print(selectedTasks, file=sys.stderr)
print(request.args.get('id'), file=sys.stderr)
print(selectedTasks[1]['id'], file=sys.stderr)
此打印:
[{'id': 1, 'title': 'Buy groceries', 'description': 'Milk, Cheese, Pizza, Fruit, Tylenol', 'done': False}, {'id': 2, 'title': 'Learn Python', 'description': 'Need to find a good Python tutorial on the web', 'done': False}]
2
2
所以任务都在那里,request.args.get('id')
是正确的,而第二个任务具有ID 2
。那么为什么这不起作用呢?
是否有'2'或''2''? (一个字符串?) –
提供一些关于谁是“请求”的代码,重要的是什么类型的id。 –
@WillemVanOnsem哦,那可能吧! request.args是url参数。所以我从这个URL获得ID:http://.../api/v1.0/tasks?id = 2。 –