python - 如何避免 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
我不想动态创建变量:当匹配列表中的元素时,我需要增加这个计数器列表(放置在另一个循环函数中)。可能相关的是,这个计数器列表被放置在一个函数内,并且在一系列嵌套循环之后
解决方案
这是你想要的吗:
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
推荐阅读
- python - Python coding: "Return a string stating the day of the week corresponding to datetime dt"
- algorithm - 如何为倒角算法创建距离图像?
- c# - SignInManager.SignInAsync(.....) 没有让我在 ASP.NET Core Blazor 中登录
- node.js - 使用 rabbitmq 对节点项目进行 Dockerising
- angular - 以角度动态更新摩纳哥编辑器主题
- parsing - SOLR 完全匹配结果不匹配
- javascript - 将 Js 变量转为元数据
- kotlin - 带有 kotlinx.html 的 json 脚本
- javascript - React-contextmenu 正在接收右键单击的错误触发器
- php - 获取当前页面链接哪个更好 - get_permalink() 或 get_page_link()?