<p>这实际上是一个非常简单的<a href="http://www.youtube.com/watch?v=pShL9DCSIUw" rel="nofollow">list comprehension</a>:</p>
<pre><code>>>> text = '000 001 002 003 '
>>> words = ['foo', 'bar', 'that', 'these']
>>> [words[int(item)] for item in text.split()]
['foo', 'bar', 'that', 'these']
</code></pre>
<p>编辑:如果需要保留其他值,可以满足以下要求:</p>
<pre><code>def get(seq, item):
try:
return seq[int(item)]
except ValueError:
return item
</code></pre>
<p>然后简单地使用像<code>[get(words, item) for item in text.split()]</code>这样的东西-当然,如果字符串中有其他数字可能会被意外替换,那么<code>get()</code>中可能需要更多的测试。(编辑结束)</p>
<p>我们要做的是将文本分割成单独的数字,然后将它们转换成整数,并使用它们来索引您给出的查找单词的列表。</p>
<p>至于为什么你的代码不能工作,主要的问题是你在字符串上循环,这会给你字符,而不是单词。不过,这不是解决问题的好办法。</p>
<p>还值得一提的是,当循环遍历值并希望索引与它们一起使用时,应该使用<a href="http://docs.python.org/3.3/library/functions.html#enumerate" rel="nofollow">the ^{<cd3>} builtin</a>,而不是使用计数变量。</p>
<p>例如:代替:</p>
<pre><code>y = -1
for w in text:
y = y + 1
...
</code></pre>
<p>使用:</p>
<pre><code>for y, w in enumerate(text):
...
</code></pre>
<p>这是更可读和Python。</p>
<p>现有代码的另一个特点是:</p>
<pre><code>w = {x:a}
for i, j in w.iteritems():
text = text.replace(i, j)
</code></pre>
<p>如果你仔细想想,可以简化为:</p>
<pre><code>text = text.replace(x, a)
</code></pre>
<p>你将<code>w</code>设置为一个项的字典,然后循环它,但是你知道它将永远只包含一个项。</p>
<p>更接近于您的方法的解决方案如下:</p>
<pre><code>words_dict = {"{0:03d}".format(index): value for index, value in enumerate(words)}
for key, value in words_dict.items():
text = test.replace(key, value)
</code></pre>
<p>我们创建一个从零填充数字字符串(使用<a href="http://docs.python.org/3.3/library/string.html#formatexamples" rel="nofollow">^{<cd5>}</a>)到值的字典,然后替换每个项。注意,当您使用2.x时,您需要<code>dict.iteritems()</code>,如果您是2.7之前的版本,请在元组生成器上使用内置的<code>dict()</code>,因为dict理解不存在。</p>