python - 两个 int 对象之间的条件检查
问题描述
我在 for 循环中迭代,构造一个列表,同时将该列表的最后一个数字与另一个数字进行比较。
我希望我的代码查看列表的最后一项是否小于与之比较的项,如果是,则将其添加到列表的末尾,然后继续。
如果列表的最后一项较大,我想弹出列表的最后一项。然后,我想对其施加相同的条件。
这是我的代码,它不起作用,它不会在弹出列表的最后一项后重新检查条件。
if tempList:
lastNum=tempList[-1]
#############################################
if element < lastNum:
incList.append(tempList)
tempList.pop()
lastNum=tempList[-1]
#############################################
elif lastNum < element:
tempList.append(element)
continue
解决方案
您可以将其捆绑到一个函数中:
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)
输出:
[3, 5, 7, 9, 11, 13] # start
[3, 5, 7, 9, 10] # after adding 10
[3, 5, 6] # after addding 6
[3, 5, 6, 10] # after adding 10
[3, 5, 6, 10, 10] # after adding 10 again
[-10] # after adding -10
为什么还要返回列表:链接示例:
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]
推荐阅读
- javascript - 适当地使用 onClick
- mysql - 更改 MariaDB 排序规则不适用于实时机器,但适用于本地机器
- arrays - 对模块内的 numpy 数组进行的操作会影响模块外的变量
- nfc - 这是哪个NFC标签?nfc-list Mifare Ultralight/Classic 7Byte UID
- python - 在 opecv python 中处理 4 个不同的视频源
- data-binding - 当页面上的自定义视图中发生属性更改时如何调用页面方法背后的代码
- ios - 为什么在 Swift 中使用来自 Firestore 的侦听器获取数据时仍然会删除文档?
- wordpress - 选项页面中的 ACF 中继器字段(木材)
- spring-mvc - 将多个对象绑定到 JSP form:form 标记中
- ios - 我正在尝试通过 WCF 服务从 sql server 获取数据