首页 > 解决方案 > 重复相同的代码块以创建不同的值

问题描述

我正在制作一个程序,该程序基本上计算多个列表中的缺失值(本例中为 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]

现在这是我的问题,我想在不编写相同代码的情况下对所有其他列表重复此步骤。这可能吗?

标签: pythonpython-3.x

解决方案


尝试把它放在这样的函数中:

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)


推荐阅读