<p>您在迭代中不断地覆盖变量的值。<code>sequence</code>和<code>description</code>仅在迭代完成时保存最后的值。你知道吗</p>
<p>相反,首先创建dictionary<strong>并将其添加到dictionary中,作为一个更复杂的数据结构,dictionary可以容纳更多的数据。你知道吗</p>
<hr/>
<p>然而,有一个更简单的方法。。。你知道吗</p>
<p>首先,您需要打开文件并读取行。为此,可以使用<a href="https://stackoverflow.com/questions/1369526/what-is-the-python-keyword-with-used-for">^{<cd3>} context manager</a>:</p>
<pre><code>with open('file_path', 'r') as f:
# used strip() to remove '\n'
lines = [line.strip() for line in f]
</code></pre>
<p>现在所有的行都在一个名为<code>lines</code>的列表中,您需要在描述和序列之间创建一个映射。你知道吗</p>
<p>如果描述行正好位于序列行上方,请使用<a href="https://stackoverflow.com/questions/509211/explain-pythons-slice-notation">slicing</a>:</p>
<pre><code># take every other line (intervals of 2) starting from index 0
descriptions = lines[0::2]
sequences = lines[0::2]
</code></pre>
<p>现在使用<a href="https://docs.python.org/2/library/functions.html#zip" rel="nofollow noreferrer">^{<cd5>}</a>将它们压缩在一起,并从每一对创建映射:</p>
<pre><code>result = dict(zip(descriptions, sequences))
</code></pre>
<p>如果是另一种情况,你可以使用这个相反的方法:</p>
<pre><code>result = dict(zip(lines[1::2], lines[0::2]))
</code></pre>
<h2>编辑:</h2>
<p>在更新之后,假设每个序列都有一个描述(准确地说),那么这样做的方法似乎是将行列表拆分为一半,然后压缩:</p>
<pre><code>middle = len(lines) / 2
result = dict(zip(lines[:mid], lines[mid:]))
</code></pre>