擅长:python、mysql、java
<p>为了进一步阐述皮耶特先生的回答和辩方提出的<a href="https://stackoverflow.com/questions/25122691/output-string-split-into-array-elements-in-one-line/25122996#comment39100653_25122691">comment</a></p>
<p>如果<code>str.split()</code>返回的值超过您允许的值,它将与<code>ValueError: too many values to unpack</code>断开。在Python 3中,您可以</p>
<pre><code>first, second, third, *extraWords = str.split()
</code></pre>
<p>这将把所有额外的内容都转储到名为<code>extraWords</code>的列表中。但是,对于Python 2,它会变得更加复杂,不像<a href="https://stackoverflow.com/questions/10792970/python-star-unpacking-for-version-2-7">this question and answer</a>中描述的那样方便。</p>
<p>或者,您可以更改存储变量的方式,并使用理解功能将其放入字典中。</p>
<pre><code>>>> words = {i:word for i,word in enumerate(myString.split())}
>>> words
{0: 'alpha', 1: 'beta', 2: 'gamma'}
</code></pre>
<p>这样做的好处是避免将所有值一起解包(我认为这在Python 2中并不理想)。但是,这可能会混淆变量名,因为它们现在被称为<code>words[0]</code>,而不是更具体的名称。</p>