首页 > 解决方案 > for循环同时减少列表的大小

问题描述

所以我有一个包含 5 个或更少元素的列表,这些元素只是 0-9 的整数,并且元素是随机分配的,列表可能有 5 个零或 5 个等,我有以下功能来检查是否列表中有一个零。这将返回它找到的第一个零的索引。只需忽略 .getValue()

    def check0(self):
        '''
        check for the index of the first card with value 0 in hand
        :return:
        '''
        index = 0
        found = False
        while not found and index<len(self.hand):
            if self.hand[index].getValue() == 0:
                found = True
            index += 1
        if not found:
            index = -1
        return index

但问题是它总是返回它在列表中找到的第一个零。在另一堂课中,我正在使用这个函数来检查手是否有零。

我需要编写一个 for 循环或其他循环来遍历列表手并告诉我手上的所有元素是否都为零。

所以对于这个问题我能想到的唯一解决方案是遍历列表一次,当找到第一个零时,增加计数器,然后这次再次遍历列表,排除已经找到的零。

例如:

I have the list
[0,0,0,0,0]

in the first traversal, the check0() method will return the index 0 for the first zero but then I traverse the list again this time excluding the first zero and repeating that until I reach the last element.

我在想这样的事情:

def find_zeros():
counter = 0
     for I in some_list(0,len(some_list),-1):
          if I.check0() != -1:
              counter += 1
          if counter == len(some_list):
             return True
     return False

谁能帮我解决这个问题?让我知道是否有任何不清楚的地方,我也不允许导入任何东西,时间复杂度不是问题

标签: pythonfor-loopwhile-loop

解决方案


“我需要编写一个 for 循环或其他循环来遍历列表手,并告诉我手上的所有元素是否都为零。” (OP)

好吧,要检查列表中的所有元素是否为零,您可以使用count

lst1 = [0,0,0,0,0]
print(len(lst1) == lst1.count(0))

或者也许列表理解:

lst1 = [0,0,0,0,0]
print(lst1 == [nr for nr in lst1 if nr == 0])

可能更好地使用如下方式编写all

lst1 = [0,0,0,0,0]
print(all(i==0 for i in lst1))

或者也许创建第二个相同大小的列表:

lst1 = [0,0,0,0,0]
print(lst1 == [0]*len(lst1))

推荐阅读