[英]Is there a more Pythonic way to loop through a list and then have each loop variable update a dictionary?
I am trying to write a more pythonic or a more concise way and avoid writing too many for loops. 我正在尝试编写一种更Python化或更简洁的方法,并避免编写过多的for循环。
Basically I have the following block code: 基本上我有以下代码:
result = {}
for model_name in list_of_model_names:
model_fields = _do_something(model_name)
result['{}_fields'.format(model_name)] = model_fields
return result
In essence, I am looping through a list of strings. 本质上,我在遍历字符串列表。 Each string I will perform some action so that some derivative of that string becomes a key and value pair in a dictionary. 我将对每个字符串执行一些操作,以使该字符串的某些派生成为字典中的键和值对。
I am reading through http://www.u.arizona.edu/~erdmann/mse350/topics/list_comprehensions.html 我正在阅读http://www.u.arizona.edu/~erdmann/mse350/topics/list_comprehensions.html
I know that : 我知道 :
My code is working, I was wondering if there's a more concise or a more pythonic way to loop through a list and have its loop variable affect the key and value of a dictionary. 我的代码正在运行,我想知道是否有更简洁或更Python的方式遍历列表,并使其循环变量影响字典的键和值。
You can be more concise using: 您可以使用以下方法更简洁:
result = {(name+'_fields'): _do_something(name) for name in list_of_model_names}
Whether that's more readable, or useful is up to you though. 究竟是可读性还是有用性取决于您。
Generally, the more Pythonic way is not to use map
, filter
, and reduce
, but to use comprehensions. 通常,更Python化的方法不是使用map
, filter
和reduce
,而是使用comprehensions。
For your code, that would be 对于您的代码,那将是
result = {'{}_fields'.format(model_name): _do_something(model_name)
for model_name in list_of_model_names}
Comprehensions can also work for lists and sets. 理解也可以用于列表和集合。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.