擅长:python、mysql、java
<p>如果有嵌套的<code>list</code>,可以尝试使用列表理解:</p>
<pre><code>routine = [['Dumbell Press', 'Chest Press Machine', 'Smith Machine Bench Press', 'Angled Dips'], [], [], [], ['Tricep Kickbacks', 'Overhead Dumbell Extensions'], [], []]
new_routine = [machine for machines in routine for machine in machines]
print(new_routine)
# ['Dumbell Press', 'Chest Press Machine', 'Smith Machine Bench Press', 'Angled Dips', 'Tricep Kickbacks', 'Overhead Dumbell Extensions']
</code></pre>
<p>只有当你有<code>list</code>的<code>lists</code>或两个级别的深度时,这才有效。你知道吗</p>
<p>要更改代码,我们可以执行以下操作以获得相同的结果:</p>
<pre><code>newarray = []
for x in range(len(routine)):
for i in range(len(routine[x])):
newarray.append(routine[x][i])
print(newarray)
#['Dumbell Press', 'Chest Press Machine', 'Smith Machine Bench Press', 'Angled Dips', 'Tricep Kickbacks', 'Overhead Dumbell Extensions']
</code></pre>
<p>注意,我从代码中删除了<code>-1</code>。<code>range(start, end)</code>从<code>start</code>到<code>end-1</code>也就是整个数组,因为数组从<code>0</code>开始。也就是说,你不需要<code>-1</code>。你知道吗</p>