Skip to main content
 首页 » 编程设计

python之索引列表的反转列表

2025年05月04日11Terrylee

我有一个索引列表列表,例如,

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]]