Python 按类型从嵌套列表中的列表中删除元素

Python 按类型从嵌套列表中的列表中删除元素,python,nested-lists,Python,Nested Lists,我正在编写一个函数,它接受一个列表列表,并且应该计算列表中每列的平均值,但是列表的前三个空格是字符串,而接下来的六个空格是我要平均的整数。我不知道如何从列表列表中删除所有字符串,以便只计算整数的平均值。以下是我目前的代码: def display_averages(input_list): print (input_list) #This is here to see that the input list is correctly nested. Will be removed onc

我正在编写一个函数,它接受一个列表列表,并且应该计算列表中每列的平均值,但是列表的前三个空格是字符串,而接下来的六个空格是我要平均的整数。我不知道如何从列表列表中删除所有字符串,以便只计算整数的平均值。以下是我目前的代码:

def display_averages(input_list):
    print (input_list) #This is here to see that the input list is correctly nested. Will be removed once the code works
    for i in input_list: #This should be the bit that removes all strings, but doesn't
        if type(i) is str:
                    input_list.remove(i)
    temp = (sum(i) for i in zip(*input_list))
    fin = []
    for l in temp:
        fin.append(l / len(input_list))
    print("MDL: Mean-",fin[0])
    print("SPT: Mean-",fin[1])
    print("HRP: Mean-",fin[2])
    print("SDC: Mean-",fin[3])
    print("LTK: Mean-",fin[4])
    print("2MR: Mean-",fin[5])
输入内容将大致如下:

temp_data = [['FIRSTNAME', 'LASTNAME', 'CATEGORY', 0, 20, 50, 0, 30, 90]]
temp_data.append(['FIRSTNAME', 'LASTNAME', 'CATEGORY', 100, 80, 100, 50, 90, 100])
display_averages(temp_data)
预期的产出将是:

MDL: Mean- 50.0
SPT: Mean- 50.0
HRP: Mean- 75.0
SDC: Mean- 25.0
LTK: Mean- 60.0
2MR: Mean- 95.0
MDL: Mean- 50.0
SPT: Mean- 50.0
HRP: Mean- 75.0
SDC: Mean- 25.0
LTK: Mean- 60.0
2MR: Mean- 95.0

假设前三个元素是字符串,其余六个是数字,
以下是平均值列表:

print([sum(l[3:]) / 6 for l in temp_data])

假设前三个元素是字符串,其余六个是数字,
以下是平均值列表:

print([sum(l[3:]) / 6 for l in temp_data])

您可以使用
numpy
包来处理2d数组(列表列表),它还为您提供了类似
mean
的功能

试试这个:

import numpy as np

arr = np.array(temp_data)
info = { "MDL": 3, "SPT": 4, "HRP": 5, "SDC": 6, "LTK": 7, "2MR": 8 } # Temp dict stores respective key-column

for k, v in info.items():
    info[k] = arr[:, v].astype(float).mean()
    print(f"{k}: Mean-", info[k])
输出:

import numpy as np

arr = np.array(temp_data)
info = { "MDL": 3, "SPT": 4, "HRP": 5, "SDC": 6, "LTK": 7, "2MR": 8 } # Temp dict stores respective key-column

for k, v in info.items():
    info[k] = arr[:, v].astype(float).mean()
    print(f"{k}: Mean-", info[k])

您可以使用
numpy
包来处理2d数组(列表列表),它还为您提供了类似
mean
的功能

试试这个:

import numpy as np

arr = np.array(temp_data)
info = { "MDL": 3, "SPT": 4, "HRP": 5, "SDC": 6, "LTK": 7, "2MR": 8 } # Temp dict stores respective key-column

for k, v in info.items():
    info[k] = arr[:, v].astype(float).mean()
    print(f"{k}: Mean-", info[k])
输出:

import numpy as np

arr = np.array(temp_data)
info = { "MDL": 3, "SPT": 4, "HRP": 5, "SDC": 6, "LTK": 7, "2MR": 8 } # Temp dict stores respective key-column

for k, v in info.items():
    info[k] = arr[:, v].astype(float).mean()
    print(f"{k}: Mean-", info[k])