擅长:python、mysql、java
<p>像这样更有活力的怎么样?你知道吗</p>
<pre><code>data = [1, 7, 2, 1, 1, 1, 2, 2, 7, 1, 7, 7, 2]
index_dict = {}
for i in range(len(data)):
# Get or create the entry for the value
sub_dict = index_dict.setdefault(val, [])
# Add the index for the value
sub_dict.append(i)
</code></pre>
<p>此代码将为遇到的每个值创建一个条目并存储其索引。然后你可以查字典知道每个值的索引。你知道吗</p>
<p>虽然这段代码没有列表理解那么优雅,但它的优点是只遍历数据一次。你知道吗</p>