Skip to main content
 首页 » 编程设计

python :不明白 "while len(list1) and len(list2):"

2025年05月04日1498°冷暖

我正在学习 Python 并正在学习谷歌代码类(class)。在 list2.py 示例中,他们要求我们编写一个函数:

Given two lists sorted in increasing order, create and return a merged list of all the elements in sorted order. You may modify the passed in lists. Ideally, the solution should work in "linear" time, making a single pass of both lists.

他们给出了代码:

def linear_merge(list1, list2): 
  result = [] 
  #Look at the two lists so long as both are non-empty. 
  #Take whichever element [0] is smaller. 
  while len(list1) and len(list2):  
    if list1[0] < list2[0]: 
      result.append(list1.pop(0)) 
    else: 
      result.append(list2.pop(0)) 
 
  #Now tack on what's left 
  result.extend(list1) 
  result.extend(list2) 
  return result 

我只是有一个关于 while 循环的问题。我不确定我是否理解 bool 测试是什么以及它何时失败并中断循环。谁能帮助我更好地理解这一点?

请您参考如下方法:

while len(list1) and len(list2): 这意味着,如果 len(list1) 和 len(list2) 是 True,换句话说 len(list1)>0 和 len(list2)>0,启动 while 循环。因此,如果在 while 循环之前这两个列表都是空的,则不会进入循环。

Python 值和容器可以用作 bool 值(真或假)。如果值是某种零,或者容器是空的,它被认为是 False,否则它是 True。

例子:

>>> a=0 
>>> bool(a) 
False 
>>> a=26 
>>> bool(a) 
True 
>>> a="" 
>>> bool(a) 
False 
>>> a=" " #this has a gap, its not "".Realize that, its different than the last example. 
>>> bool(a) 
True 
>>>  

此外,在 Python 中, bool 值 True 或 False 可用于算术:False 的算术值为零,True 的算术值为 1。

例子:

>>> True + True 
2 

通常在 Python 中使用 while True: 并在您想要的地方用 if 语句跳出循环会更好。但对于此 linear_merge() 函数而言,这不是必需的。

例子:

while True: 
    #codes 
    if <SomethingHappensThatYouWantToStopTheLoop>: 
        break