列表列表(求和索引但需要跳过某些索引('无'值)

时间:2014-11-27 20:04:53

标签: python list indexing

我有一个列表列表(training_list)。每个列表有15个索引。我需要总结每个列表的每个索引,例如list1 row [0] + list2 row [0]等等。

我创建了允许我这样做的功能 - def sums_list。但是,当我的代码将每个索引汇总在索引2中时,由于None值,我遇到了问题。该值也包含在索引3& 13.

我无法替换此None值,我需要保持原样。我希望基本上跳过这个并继续下一个索引。

training_list = [
    [22, 0.7173543689320389, None, None, 10, 0.4122977346278317,
     0.10788834951456311, 0.038187702265372166, 0.8373381877022654,
     0.6119741100323625, 0, 0, 38, None, ' <=50K'],
    [28, 0.7173543689320389, None, None, 5, 0.4122977346278317,
     0.12823624595469255, 0.3013349514563107, 0.8373381877022654,
     0.6119741100323625, 0, 0, 40, None, ' <=50K'],
    [30, 0.7173543689320389, None, None, 13, 0.3351132686084142,
     0.09227346278317151, 0.033292880258899676, 0.8373381877022654,
     0.38802588996763754, 0, 0, 40, None, ' >50K'],
    [20, 0.7173543689320389, None, None, 10, 0.4122977346278317,
     0.051941747572815535, 0.20230582524271845, 0.8373381877022654,
     0.6119741100323625, 0, 0, 20, None, ' >50K']
]

代码:

def sums_lists(list1, list2):
    try:
        sums_list = []
        for index in range(14):
            sums_list.append(list1[index]+list2[index])
    except:
        pass
    return sums_list

def make_averages(sums_list, total_int):

    try:
        average_list = []
        for value_int in sums_list:
            average_list.append(value_int/total_int)
    except:
        pass
    return average_list

def train_classifier(training_list):
    under_50k_sums_list = [0]*14 
    under_50k_count = 0 
    over_50k_sums_list = [0]*14 
    over_50k_count = 0 


    for row in training_list:
        if row[-1] == ' <=50K':

            under_50k_sums_list = sums_lists(under_50k_sums_list, row[:-1])
            under_50k_count += 1
        else: 
            over_50k_sums_list = sums_lists(over_50k_sums_list, row[:-1])
            over_50k_count += 1

            under_50k_averages_list = make_averages(under_50k_sums_list, under_50k_count)
            over_50k_averages_list = make_averages(over_50k_sums_list, over_50k_count)


        classifier_list = make_averages(sums_lists(under_50k_averages_list, over_50k_averages_list),2)

    return classifier_list

1 个答案:

答案 0 :(得分:0)

试试这个:

def sums_lists(list1, list2):
    zipped = zip(list1,list2)
    result = []
    for item in zipped[:-1]:
        if None not in item:
            result.append(sum(item))
    return result

如果只有最后的部分可以是字符串,则可以在求和中跳过该部分。