【问题标题】:Best solution for a loop inside of a loop in pythonpython中循环内循环的最佳解决方案
【发布时间】:2019-01-27 11:34:45
【问题描述】:

例如:

result=[]
todolist=mongo.db.Todo.find()
for todo in todolist:
    for detail in todo['list']:
        result.append(str(detail))

我正在寻找避免嵌套 for 循环的最佳方法。 我是新手。 谁能帮我?谢谢。

【问题讨论】:

  • 你的嵌套循环有什么问题?
  • 你有类似result = [str(detail) for todo in todolist for detail in todo['list']]的列表理解吗?
  • 好的,我删除了我的答案,因为你说你不想使用for 循环。
  • 我的意思是我想避免嵌套 for 循环。

标签: python json mongodb


【解决方案1】:

我认为这是您正在寻找的“循环内循环的最佳方式”:

results = [str(detail) for todo in todolist for detail in todo['list']]

将其转换为 json:

import json

json_result = json.dumps(results)

【讨论】:

  • 这不会被认为是一个for循环吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多