擅长:python、mysql、java
<p>鉴于:</p>
<pre><code>>>> li
['cat', 'dog', 'chicken']
</code></pre>
<p>你可以做:</p>
<pre><code>>>> [e for s in li for e in [s,s,s]]
['cat', 'cat', 'cat', 'dog', 'dog', 'dog', 'chicken', 'chicken', 'chicken']
</code></pre>
<p>或者,由于字符串是固定不变的,如果您也这样做,您不会感到意外:</p>
<pre><code>>>> [e for s in li for e in [s]*3]
['cat', 'cat', 'cat', 'dog', 'dog', 'dog', 'chicken', 'chicken', 'chicken']
</code></pre>
<p>这是对Alex Martelli的<a href="https://stackoverflow.com/a/952952/298607">answer</a>关于如何展平列表的修改。在本例中,<code>[s, s, s]</code>或字符串3次</p>
<p>如果您正在读取文件,则可以执行以下操作:</p>
<pre><code>n=3
with open(ur_file) as f_in:
flat_list=[word for line in f for word in line.split()]
duped_words=[mult for word in flat_list for mult in [s]*n]
</code></pre>