Python 无法理解循环中的条件语句
Python Can't understand conditional statement in loop
在 python 需要帮助。此代码来自 leetcode.com, one of the solutions for this problem 并且无法理解那里的条件语句,正是代码“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
它返回堆栈最后一个索引中的第二个元素
例如,如果堆栈是一个字符串列表,例如
stack = ['abc','def','ghi']
比堆栈[-1][1] returns
stack[-1] <-- 'ghi'
stack[-1][1] <-- 'h'
在 python 需要帮助。此代码来自 leetcode.com, one of the solutions for this problem 并且无法理解那里的条件语句,正是代码“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
它返回堆栈最后一个索引中的第二个元素
例如,如果堆栈是一个字符串列表,例如
stack = ['abc','def','ghi']
比堆栈[-1][1] returns
stack[-1] <-- 'ghi'
stack[-1][1] <-- 'h'