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)
In [1]: from collections import defaultdict
In [2]: data = [1, 7, 2, 1, 1, 1, 2, 2, 7, 1, 7, 7, 2]
In [3]: indices = defaultdict(list)
In [4]: for i, d in enumerate(data):
...: indices[d].append(i)
...:
In [5]: indices
Out[5]: defaultdict(<class 'list'>, {1: [0, 3, 4, 5, 9], 2: [2, 6, 7, 12], 7: [1, 8, 10, 11]})
虽然werkzeug并不适合这份工作,但它会很好地工作:
像这样更有活力的怎么样?你知道吗
此代码将为遇到的每个值创建一个条目并存储其索引。然后你可以查字典知道每个值的索引。你知道吗
虽然这段代码没有列表理解那么优雅,但它的优点是只遍历数据一次。你知道吗
您可以使用^{} 来收集每组元素的索引:
相关问题 更多 >
编程相关推荐