2017-06-19 129 views
0

我有一个任务列表,我试图选择具有给定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。那么为什么这不起作用呢?

+8

是否有'2'或''2''? (一个字符串?) –

+0

提供一些关于谁是“请求”的代码,重要的是什么类型的id。 –

+0

@WillemVanOnsem哦,那可能吧! request.args是url参数。所以我从这个URL获得ID:http://.../api/v1.0/tasks?id = 2。 –

回答

2

request.args,该id是一个字符串,并在2等于'2'

>>> 2 == '2' 
False 

所以我们可以简单地将字符串转换为int(..),并解决它像:

if 'id' in request.args: 
    the_id = int(request.args.get('id')) 
    selectedTasks = [task for task in selectedTasks if task['id'] == the_id]

或者,y OU可以 - 像你说的自己 - 提供type参数来.get()方法做转换在.get()级别:

if 'id' in request.args: 
    the_id = request.args.get('id',type=int) 
    selectedTasks = [task for task in selectedTasks if task['id'] == the_id]
+0

我用'request.args.get('id',type = int)',但基本上我也这么想。我觉得它看起来更好。是否有理由在'.get('id',type = int)''上使用'int(...)'? –

+0

@TheOddler:完全没有。我认为这确实是一种更优雅的方式。我已经更新了答案。感谢您的反馈。 –

1

您没有指定用于提供请求对象的框架,但很有可能request.args确实返回了一个字符串列表。您应该尝试将请求参数转换为int。

if 'id' in request.args: 
    task_id = request.args.get('id') 
    assert task_id.isdigit() 
    task_id = int(task_id) 
    selectedTasks = [task for task in selectedTasks if task['id'] == task_id] 
相关问题