For 循环以奇怪的顺序选择图像

我的静态目录中有一个结果文件夹,其中包含九张名为“result_1.jpg”到“result_9.jpg”的图像,我想在我的 html 页面的网格中以正确的顺序显示它们。

一切正常,除了输出顺序完全随机但始终相同。

这是我的python片段:

@app.route('/fResults/')
def show_fResults():
    imgs = os.listdir('static/results/')
    imgs = ['results/' + file for file in imgs]
    return render_template('fResults.html',imgs = imgs)

这是我的 html 片段:

<div class="resultGrid">
    {% for img in imgs %}
    <div class="resultImages">
        <img id="results" src="{{ url_for('static',filename = img) }}" alt="{{loop.index}}">
    </div>
    {% endfor %}
</div>

这里是 html 输出:

html output

有没有办法强制它使用给定的顺序?

先谢谢你!

编辑:多亏了 Epsi95,我才能够解决我的问题。

@Epsi95 非常感谢!

hdswphr 回答:For 循环以奇怪的顺序选择图像

os.listdir 的输出有点随机,但实际上并不总是相同的。这取决于您要求操作系统的文件系统为您提供文件时的感受。

您需要做的是自己在应用程序中对列表进行排序。 Python 有一个名为 sorted() 的内置排序函数。

你可以这样使用它:

@app.route('/fResults/')
def show_fResults():
    imgs = sorted(os.listdir('static/results/'))
    imgs = ['results/' + file for file in imgs]
    return render_template('fResults.html',imgs = imgs)

现在它们将始终处于相同的排序顺序,无论 os.lisdir() 返回的顺序如何。

本文链接:https://www.f2er.com/1260.html

大家都在问