【问题标题】:Is there a more Pythonic way to loop through a list and then have each loop variable update a dictionary?有没有更 Pythonic 的方式来遍历一个列表,然后让每个循环变量更新一个字典?
【发布时间】:2018-04-23 06:05:14
【问题描述】:

我正在尝试写一个更pythonic或更简洁的方式,避免写太多的for循环。

基本上我有以下块代码:

result = {}
for model_name in list_of_model_names:
    model_fields = _do_something(model_name)
    result['{}_fields'.format(model_name)] = model_fields
return result

本质上,我正在遍历一个字符串列表。我将对每个字符串执行一些操作,以便该字符串的某些派生成为字典中的键值对。

我正在阅读http://www.u.arizona.edu/~erdmann/mse350/topics/list_comprehensions.html

我知道:

  1. 地图返回一个列表
  2. 过滤器减少了元素的数量
  3. Reduce 看起来会返回列表中的本机数据类型。可能是字符串或数字,具体取决于原始列表。

我的代码正在运行,我想知道是否有更简洁或更 Pythonic 的方式来循环遍历列表并使其循环变量影响字典的键和值。

【问题讨论】:

  • 使用字典理解 - {'{}_fields'.format(m) : _do_something(m) for m in list_of_model_names}?

标签: python list dictionary


【解决方案1】:

一般来说,更 Pythonic 的方式不是使用 mapfilterreduce,而是使用推导式。

对于您的代码,那将是

result = {'{}_fields'.format(model_name): _do_something(model_name)
          for model_name in list_of_model_names}

理解也适用于列表和集合。

【讨论】:

    【解决方案2】:

    您可以更简洁地使用:

    result = {(name+'_fields'): _do_something(name) for name in list_of_model_names}
    

    这是否更具可读性或有用性取决于您。

    【讨论】:

      猜你喜欢
      • 2018-12-29
      • 1970-01-01
      • 2021-11-12
      • 2011-05-04
      • 1970-01-01
      • 2019-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多