我有一个索引列表的列表,例如,
a = [
[2],
[0, 1, 3, 2],
[1],
[0, 3]
]
我现在想“反转”此列表:数字0
出现在索引1
和3
,所以:
b = [
[1, 3],
[1, 2],
[0, 1],
[1, 3]
]
关于如何快速执行操作的任何提示?(我正在处理的列表可能很大。)
奖励:我知道每个索引都出现两次a
(就像上面的示例一样)。
此代码不依赖于每个数字恰好出现两次的事实。它也非常简单,避免了构建字典然后从那里复制结果的开销:
a = [
[2],
[0, 1, 3, 2],
[1],
[0, 3]
]
b = []
for i, nums in enumerate(a):
# For each number found at this index
for num in nums:
# If needed, extend b to cover the new needed range
b += [[] for _ in range(num + 1 - len(b)]
# Store the index
b[num].append(i)
print(b)
# Output:
# [[1, 3], [1, 2], [0, 1], [1, 3]]
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句