python在def函数中使用for循环

时间:2021-06-24 02:46:11

标签: python function for-loop structure

我试图在数据库集合中获取过去 7 天内创建的文档。

fmt = "%Y-%m-%d"
today = datetime.now(timezone('Asia/Seoul'))
for i in range(0, 7):
    target = today - timedelta(days = i)
    week = target.strftime(fmt)
    hot_posts = list(db.collection.find({'date': week}, {'_id': False}).sort('like', -1))
    print(hot_posts)

这为我提供了我正在从数据库中寻找的正确文档集。

但是当我在 def 函数中插入它时,它不起作用。

fmt = "%Y-%m-%d"
today = datetime.now(timezone('Asia/Seoul'))
@app.route('/api/list/hot', methods=['GET'])
def show_hot():
    for i in range(0, 7):
        target = today - timedelta(days=i)
        week = target.strftime(fmt)
        hot_posts = list(db.collection.find({'date': week}, {'_id': False}).sort('like', -1))
        return jsonify({'hot_posts': hot_posts})

我不认为我完全理解如何在正确的结构中使用 def。 在这种情况下,在 python 中使用 def 的正确格式是什么? 我是否需要在 for 循环之前放置一些变量并将其设置为 variable=[] 以获取 for 循环的结果并将其放入 def 函数可以使用的变量中? 我是否需要将一些 for 循环变量放入 def 函数的 () 中?

类似的东西?

fmt = "%Y-%m-%d"
today = datetime.now(timezone('Asia/Seoul'))
@app.route('/api/list/hot', methods=['GET'])
def show_hot(range, list):
    hot_posts = []
    for i in range(0, 7):
        target = today - timedelta(days=i)
        week = target.strftime(fmt)
        hot_posts = list(db.collection.find({'date': week}, {'_id': False}).sort('like', -1))
    return jsonify({'hot_posts': hot_posts})

1 个答案:

答案 0 :(得分:0)

您可以创建一个空白字典并在迭代时更新它的键和值,然后返回结果字典。我还没有测试过这段代码,但我认为它应该可以正常工作。

fmt = "%Y-%m-%d"
today = datetime.now(timezone('Asia/Seoul'))
@app.route('/api/list/hot', methods=['GET'])
def show_hot():
    all_hot_posts = {}
    for i in range(0, 7):
        target = today - timedelta(days=i)
        week = target.strftime(fmt)
        hot_posts = list(db.collection.find({'date': week}, {'_id': False}).sort('like', -1))
        all_hot_posts.update({'hot_posts'+str(i+1): hot_posts})
    return jsonify(all_hot_posts)

在 Python 函数中,我们没有将关键字定义为参数。它们的解释就像普通脚本一样。