0

我最近才发现自己正在编写这行代码,我不太喜欢它:

if ('upload' in request.POST) or ('delete' in request.POST):

我已经考虑过列表理解,它看起来像这样:

if [value for value in ['upload','delete'] if value in request.POST]:

这并不是更好。我非常简单的问题是:这可以简化吗?或者这只是想太聪明?

4

2 回答 2

6

您可以使用 set intersection 更简洁地编写它:

if {'upload', 'delete'} & set(request.POST):

或更明确地说:

if {'upload', 'delete'}.intersection(request.POST):
于 2012-04-08T19:26:00.537 回答
1

简化使用any().

if any(value for value in ['upload','delete'] if value in request.POST):
于 2012-04-08T19:26:04.990 回答