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

Remove Elements by Type from Lists in a Nested List

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

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

鉴于前三个元素是字符串,其余六个是数字,
以下将为您提供平均值列表:

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

您可以使用 numpy 包来处理二维数组(列表的列表),它还为您提供了很好的功能,例如 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])

输出:

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