python - 重复相同的代码块以创建不同的值
问题描述
我正在制作一个程序,该程序基本上计算多个列表中的缺失值(本例中为 x)。这些是列表:
L11=[1,3,5,'x',8,10]
L12=['x',3,3,'x',6,0]
L21=[6,1,1,9,2,2]
L22=[1,1,1,'x','x','x']
例如,我正在使用此代码块来查找 L22 中的 x 值:
#How to find x:
#1--> a= calculate the sum of integers in the list
#2--> b=calculate the average of them
#3--> all values of x inside the list equal b
a22=L22.count('x')
for i in range(len(L22)):
if L22[i]=='x':
x_L22=round((sum([int(k) for k in L22 if type(k)==int]))/(len(L22)-a22))
所以我们发现 x_L22=1 并且新的 L22 是:
x_L22=1
L22=[1,1,1,1,1,1]
现在这是我的问题,我想在不编写相同代码的情况下对所有其他列表重复此步骤。这可能吗?
解决方案
尝试把它放在这样的函数中:
def list_foo(list_):
counted=list_.count('x')
for i in range(len(list_)):
if list_[i]=='x':
total=round((sum([int(k) for k in list_ if type(k)==int])) \
/(len(list_)-counted))
return total
在你的主循环中使用它
x_L22 = list_foo(L22)
或者x_L11 = list_foo(L11)
推荐阅读
- python - PyMysql选择索引字段非常慢的地方
- c++ - Qt3D:关于 QText2DEntity 的几个简单问题
- sql - 使用置信度分数在 SQL 表中搜索重复项
- python - manim example_scenes.py 不会运行
- laravel - 如何删除相关值?
- python - 熊猫添加所有值为零的行
- excel - excel,两列的组合是一对一还是一对多
- json - 如何在golang中将http响应体解析为json格式?
- javascript - 锚标记多次附加到子 div
- python - 应用程序与 PyInstaller 捆绑时找不到 Azure CLI“登录”命令