Python 两个int对象之间的条件检查
我在for循环中迭代,构造一个列表,同时将该列表的最后一个数字与另一个数字进行比较 我想让我的代码查看列表的最后一项是否比它要比较的项小,如果是,则将其添加到列表的末尾,然后继续 如果列表的最后一项较大,我想弹出列表的最后一项。然后,我想对其附加同样的条件 这是我的代码,它不工作,它不会在弹出列表的最后一项后重新检查条件Python 两个int对象之间的条件检查,python,recursion,conditional,Python,Recursion,Conditional,我在for循环中迭代,构造一个列表,同时将该列表的最后一个数字与另一个数字进行比较 我想让我的代码查看列表的最后一项是否比它要比较的项小,如果是,则将其添加到列表的末尾,然后继续 如果列表的最后一项较大,我想弹出列表的最后一项。然后,我想对其附加同样的条件 这是我的代码,它不工作,它不会在弹出列表的最后一项后重新检查条件 if tempList: lastNum=tempList[-1] #############################################
if tempList:
lastNum=tempList[-1]
#############################################
if element < lastNum:
incList.append(tempList)
tempList.pop()
lastNum=tempList[-1]
#############################################
elif lastNum < element:
tempList.append(element)
continue
if templast:
lastNum=templast[-1]
#############################################
如果元素
您可以将其捆绑到一个函数中:
def append_if_lower_else_pop_end_from_list_until_lower(l, num):
"""Add num to l if l[-1] < num, else pop() from l until"""
while l and l[-1] > num:
l.pop()
l.append(num)
# this is not strictly needed - lists are mutable so you are mutating it
# returning it would only make sense for chaining off it with other methods
return l
k = [3,5,7,9,11,13]
print(k)
append_if_lower_else_pop_end_from_list_until_lower(k, 10)
print(k)
append_if_lower_else_pop_end_from_list_until_lower(k, 6)
print(k)
append_if_lower_else_pop_end_from_list_until_lower(k, 10)
print(k)
append_if_lower_else_pop_end_from_list_until_lower(k, 10)
print(k)
append_if_lower_else_pop_end_from_list_until_lower(k, -10)
print(k)
为什么还要返回列表:链接示例:
k = [3,5,17,9,11,13]
append_if_lower_else_pop_end_from_list_until_lower(k, 10).sort()
print(k)
输出:
[3, 5, 9, 10, 17]
试试这个:
yourlist = [3,1,4]
n = 1
resultlist = yourlist[:-1] if yourlist[-1]>=n else yourlist+[n]
print(resultlist)
n = 5
resultlist = yourlist[:-1] if yourlist[-1]>=n else yourlist+[n]
print(resultlist)
输出:
[3,1]
[3,1,4,5]我不明白你在问什么。您可以添加一个示例输入、您得到的输出和您想要得到的输出吗?我也不确定您想做什么,但我注意到您添加了
templast
,这是整个列表-我假设这应该是元素
?
yourlist = [3,1,4]
n = 1
resultlist = yourlist[:-1] if yourlist[-1]>=n else yourlist+[n]
print(resultlist)
n = 5
resultlist = yourlist[:-1] if yourlist[-1]>=n else yourlist+[n]
print(resultlist)