Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/343.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在列表上迭代,直到满足2个条件_Python_List_Loops - Fatal编程技术网

Python 在列表上迭代,直到满足2个条件

Python 在列表上迭代,直到满足2个条件,python,list,loops,Python,List,Loops,我有一个列表,我想把列表中的所有数字相加。。。 除了如果出现6,则不计算该数字以及该6中的任何数字,直到出现下一个7(也不计算7)。7总是在6之后的某个地方出现 例如: my_list = [1,2,3,6,1,1,1,7,2,2,2] 1,2,3,.........,2,2,2 # Omit numbers from the first 6 to the next 7. 应该输出12 我知道如何识别6,我只是不知道如何不计算数字,直到后续的7来 谢谢。您可以使用布

我有一个列表,我想把列表中的所有数字相加。。。 除了如果出现6,则不计算该数字以及该6中的任何数字,直到出现下一个7(也不计算7)。7总是在6之后的某个地方出现

例如:

my_list = [1,2,3,6,1,1,1,7,2,2,2]
           1,2,3,.........,2,2,2    # Omit numbers from the first 6 to the next 7.
应该输出12

我知道如何识别6,我只是不知道如何不计算数字,直到后续的7来


谢谢。

您可以使用布尔值作为标志。这应该做到:

list= [1,2,3,6,1,1,1,7,2,2,2] 
do_sum = True
total_sum = 0

for item in list:
   if item == 6:
       do_sum = False

   if do_sum:
      total_sum += item

   if not do_sum and item == 7:
       do_sum = True
最后一个if将检查6是否在7之前。因此,它将对出现在6之前的任何7求和


此解决方案支持列表中多个6和7对的情况。

让我们按照纸面上的方式执行此操作:

  • 找到第一个
    6
    ;将列表标记到该点
  • 在列表的其余部分,找到前7个;在该点之后标记列表
  • 合并两个标记的列表部分;将这些元素相加
代码,带有一行跟踪输出:

seq = [1, 2, 3, 6, 1, 1, 1, 7, 2, 2, 2]
first6 = seq.index(6)
rest = seq[first6:]
next7 = rest.index(7)
sum_list = seq[:first6] + rest[next7+1:]
print("Add these:", sum_list)
print("Sum:", sum(sum_list))
输出:

Add these: [1, 2, 3, 2, 2, 2]
Sum: 12
您可以通过组合表达式来缩短代码,但我认为在您的编程生涯的这个阶段,这对您来说更具可读性