Skip to main content
 首页 » 编程设计

python之试图理解 python 中的双索引

2025年05月04日25soundcode

def countSmaller(self, nums): 
        def sort(enum): 
            half = len(enum) / 2 
            if half: 
                left, right = sort(enum[:half]), sort(enum[half:]) 
                for i in range(len(enum))[::-1]: 
                    if not right or left and left[-1][1] > right[-1][1]: 
                        smaller[left[-1][0]] += len(right) 
                        enum[i] = left.pop() 
                    else: 
                        enum[i] = right.pop() 
            return enum 
        smaller = [0] * len(nums) 
        sort(list(enumerate(nums))) 
        return smaller 

我是一个新的 python 编码器所以这个查询!..在 left[-1][1] 中,我理解 [-1] 让我想到最后一个索引但是第二个索引 [1] 是什么意思。

请您参考如下方法:

第二个索引与第一个索引相同,但具有嵌套值。 例如:

a = [(1, 2), (2, 3), (3, 4)] 
a[-1]  # (3, 4) 
a[-1][1]  # 4 

在您的示例中,您没有带数字的列表,而是枚举转换为列表的对象

sort(list(enumerate(nums))) 

这意味着你有这样的数据:

nums = [1, 2, 3, 4, 5] 
enum_list = list(enumerate(nums))  # [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5)]