首页 > 解决方案 > 如何避免 if..then 用于一长串计数器中的元素

问题描述

我的代码中有一个计数器列表,如果可能的话,我想避免为每个计数器编写一个 if 条件。

我在python 3中找到了以下解决方案,但它不起作用....怎么办?

def myfunc():
    ...
    ...
    for a in list1:

         <do something>
         for b in list2:
             a=0
             b=0
             c=0                
             <do something>

                  for c in list3:

                       <do something>

                        if <condition> is true>:

                            for element in a list:

                            <do something>

                                  for i in ['a', 'b', 'c']:
                                      if element == i:
                                      i += 1    

我不想动态创建变量:当匹配列表中的元素时,我需要增加这个计数器列表(放置在另一个循环函数中)。可能相关的是,这个计数器列表被放置在一个函数内,并且在一系列嵌套循环之后

标签: pythonif-statement

解决方案


这是你想要的吗:

def myfunc():
     a=0
     b=0
     c=1
     l = [a,b,c]
     d=locals()
     for element,i in list(zip(l,['a','b','c'])):
          d[i]=d[i]+1
     print(d['a'])
     print(d['b'])
     print(d['c'])
myfunc()

输出:

1
1
2

推荐阅读