我正在制作一个程序,该程序基本上可以计算多个列表中的缺失值(在此示例中为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]
现在这是我的问题,我想对所有其他列表重复此步骤,而无需编写相同的代码。这可能吗?
答案 0 :(得分:0)
尝试将其放在这样的函数中:
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)
答案 1 :(得分:0)
这是Python函数的绝佳用例
def get_filled_list(list_of_numbers):
#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
new_list=list_of_numbers.count('x')
for i in range(len(list_of_numbers)):
if list_of_numbers[i]=='x':
list_of_numbers = round(
(sum([int(k)
for k in list_of_numbers if type(k)==int]))/
(len(list_of_numbers)-new_list)
)
A11 = get_filled_list(L11)
# ,..
答案 2 :(得分:0)
我要编写一个函数,该函数接收一个列表作为输入,并返回用'x'
值替换为新值的相同列表:
def calculateList(l):
nrX=l.count('x')
newList = []
for elem in l:
if elem == 'x':
x = int(round((sum([int(k) for k in l if type(k)==int]))/(len(l)-nrX)))
newList.append(x)
else:
newList.append(elem)
return newList
然后您可以在所有列表上调用此函数:
newL = calculateList(L22)
print(newL)
输出为:
[1, 1, 1, 1, 1, 1]
或者,如果您愿意,可以创建一个包含所有要评估的列表的列表:
allLists = [L11, L12, L21, L22]
然后您遍历此列表:
for l in allLists:
newL = calculateList(l)
print(newL)
输出为:
[1, 3, 5, 5, 8, 10]
[3, 3, 3, 3, 6, 0]
[6, 1, 1, 9, 2, 2]
[1, 1, 1, 1, 1, 1]
答案 3 :(得分:0)
其他答案集中在将您的当前代码提取到一个通用函数上,该函数很有用,但在多输入上应用同一段代码既不充分,也没有必要。
您唯一需要做的就是遍历数据片段:
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']
inputs = ( L11, L12, L21, L22 )
for input in inputs :
# your 4 previous lines on code, modified to work
# on the generic "input" instead of the specific "L22"
a=input.count('x')
for i in range(len(input)):
if input[i]=='x':
x=round((sum([int(k) for k in input if type(k)==int]))/(len(input)-a))
# or if you've extracted the above code to a function,
# just call it instead of using the above 4 lines of code.