擅长:python、mysql、java
<p>部分解</p>
<pre><code>names = {age:sorted([name for index,name in enumerate(NAMES) if age == AGES[index]]) for age in sorted(set(AGES))}
print(names)
</code></pre>
<p>返回:</p>
<pre><code>{18: ['Cathy', 'Dan'], 19: ['Ed', 'Helen', 'Irene', 'Jack', 'Larry'], 20: ['Alice', 'Frank', 'Gary'], 21: ['Bob'], 22: ['Kelly']}
</code></pre>
<p>如果你愿意的话,把sorted()去掉。您还可以添加count()使数据返回如下内容</p>
<pre><code>{18: [('Cathy',3), ('Dan',7), ...}
</code></pre>
<p>如果有3个凯茜和7个丹麦人。</p>
<p>尽管上面的代码看起来很短,但我怀疑实际for循环在原始列表上的迭代次数会更少。</p>
<p>或者更好:</p>
<pre><code>def names(age):
index = 0
while index < len(AGES):
if AGES[index] == age:
yield NAMES[index]
index += 1
print('19 year olds')
for name in names(19):
print(name)
</code></pre>