列表(空或已填充)与 int 的比较如何工作?

问题描述 投票:0回答:1

不明白这个 IF 语句如何将变量 res (list) 与列表中的整数 (res[start]) 进行比较。代码按预期工作,但我无法理解代码中的 IF 语句行。

items = [5, 7, 10, 4, 8, 9, 10, 2, 1, 3]
res = []
start = 0
for elem in items:
    if not res or elem <= res[start]:
        start = len(res)
    res.insert(start, elem)
print(res)

如果我只是尝试将 res 与 res[start] 进行比较:

res = []
start = 0
print(res < res[start])

我收到列表索引超出范围错误。

python list
1个回答
0
投票

您的代码中没有 int 来列出数学比较。

if 语句是一个逻辑比较,它检查是否:

条件 1:如果

not res
为 True

条件 2:如果
elem <= res[start]
为 True

因此,从数学角度来看,

res
res[start]相比
不是
。 if 语句的比较是在上面列出的两个条件之间进行的逻辑比较

顺便说一句,如果列表为空,条件 1 将返回 True,如果列表已满,则返回 False。

有关逻辑比较和具有多个条件的

if
语句的更多信息可在此处找到:

https://kodify.net/python/if-else/if-conditions/

© www.soinside.com 2019 - 2024. All rights reserved.