简体   繁体   English

Python:使用列表理解的最佳方法?

[英]Python: Best way to use a list comprehension?

I'm trying to use a list comprehension in python 2.7 to better achieve what I have now: 我正在尝试在python 2.7中使用列表理解以更好地实现我现在拥有的功能:

params['item1'] = request.GET.get('item1', '')
params['item2'] = request.GET.get('item2', '')
params['item3'] = request.GET.get('item3', '')
params['item4'] = request.GET.get('item4', '')
params['item5'] = request.GET.get('item5', '')

params['items'] = [
    params['item1'].encode('utf-8'),
    params['item2'].encode('utf-8'),
    params['item3'].encode('utf-8'),
    params['item4'].encode('utf-8'),
    params['item5'].encode('utf-8')
]

I'm wondering if a loop and list comprehension would work best (like below) But I'm also wondering if there are better ways to do this. 我想知道循环和列表理解是否最有效(如下所示),但我也想知道是否有更好的方法可以做到这一点。

params['items'] = []

for x in range(5):
    item = 'item' + str(x+1)
    params[item] = request.GET.get(item, '')
    params['items'].extend(params[item].encode('utf-8'))

Yes, a list comprehension would handle this neatly: 是的,列表推导会巧妙地处理此问题:

params["items" = [request.GET.get('item'+str(i), '').encode('utf-8')
                      for i in range(1,6) ]

"better" is a value judgment, which is out of scope for Stack Overflow. “更好”是一种价值判断,超出了堆栈溢出的范围。 Is the list comprehension easier to read and maintain than your original loop? 列表理解比原始循环更容易阅读和维护吗? That's up to you and your programming/usage team. 这取决于您和您的编程/使用团队。

Assuming params starts empty, I would split this into a dictionary comprehension and a list comprehension. 假设params开始为空,我将其分为字典理解和列表理解。 I would also change the range rather than adding one to each index: 我还将更改范围,而不是向每个索引添加一个:

 params={'item' + str(x):request.GET.get('item' + str(x), '') for i in range(1,6)}`
 params['items']=[item.encode('utf-8') for item in params.keys()]

Something else to consider is if request.GET is creating an external call every time you access it. 还有一点要考虑的是request.GET是否在每次访问它时都在创建一个外部调用。 If so, you should create one local copy and access that, eg 如果是这样,则应创建一个本地副本并访问该副本,例如

local_copy = request.GET.copy()
params={'item' + str(x):local_copy.get('item' + str(x), '') for i in range(1,6)}`

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM