<p>我使用Python,这里有一个不同文件类型的文件名列表。文本文件可能如下所示:</p>
<pre><code>01.txt
02.txt
03.txt
...
</code></pre>
<p>假设文本文件都是这样编号的。现在我想得到所有的文本文件,数字从1到25。因此,我想通过GUI提供一个类似<code>%02i.txt</code>的formatstring,以便识别所有匹配的文件名。你知道吗</p>
<p>到目前为止,我的解决方案是一个嵌套的<code>for</code>循环。外循环遍历整个列表,每个文件的内循环计数从1到25:</p>
<pre class="lang-py prettyprint-override"><code>fmt = '%02i.txt'
for f in files:
for i in range(1, 25+1):
if f == fmt % i:
# do stuff
</code></pre>
<p>这个嵌套循环看起来不太漂亮,复杂性是<em>O(n²)</em>。所以在很长的名单上可能需要一段时间。<strong>有没有更聪明的方法?</strong></p>
<p>嗯,是的,我可以使用像<code>^\d{2}\.txt$</code>这样的正则表达式,但是带有<code>%</code>的formatstring更容易键入。你知道吗</p>
<p>可以使用集合:</p>
<pre><code>fmt = '%02i.txt'
targets = {fmt % i for i in range(1, 25+1)}
</code></pre>
<p>那么</p>
<pre><code>for f in files:
if f in targets:
# do stuff
</code></pre>