首页 > 解决方案 > Python无法理解循环中的条件语句

问题描述

在 python 中需要帮助。这段代码来自leetcode.com,这个问题的解决方案之一,无法理解那里的条件语句,正是代码“ stack[-1][1]

class Solution(object):

def dailyTemperatures(self, temps):

    if not temps:
        return []

    result = [0] * len(temps)
    stack = []

    for curr_idx, curr_temp in enumerate(temps):

        while stack and curr_temp > stack[-1][1]: # not clear, and I know, it is not a type of access to list element

            last_idx, last_temp = stack.pop()
            result[last_idx] = curr_idx - last_idx

        stack.append((curr_idx, curr_temp))

    return result

标签: pythonloopsconditional-statementsstatements

解决方案


它返回堆栈的最后一个索引中的第二个元素

例如,如果堆栈是一个字符串列表,例如

stack = ['abc','def','ghi']

比 stack[-1][1] 返回

stack[-1] <-- 'ghi'
stack[-1][1] <-- 'h'

推荐阅读