代码之家  ›  专栏  ›  技术社区  ›  djennacs

Python将元组列表中的值求和到某些值

  •  0
  • djennacs  · 技术社区  · 8 年前

    我在Python中的迭代方面遇到了问题,尤其是当我想将值汇总到某个数字时。以下是关于我面临的问题的更多信息:

    我有一个元组列表,如下所示:

    [(1, 0.5, 'min'),
     (2, 3, 'NA'),
     (3, 6, 'NA'),
     (4, 40, 'NA'),
     (5, 90, 'NA'),
     (6, 130.8, 'max'),
     (7, 129, 'NA'),
     (8, 111, 'NA'),
     (9, 8, 'NA'),
     (10, 9, 'NA'),
     (11, 0.01, 'min'),
     (12, 9, 'NA'),
     (13, 40, 'NA'),
     (14, 90, 'NA'),
     (15, 130.1, 'max'),
     (16, 112, 'NA'),
     (17, 108, 'NA'),
     (18, 90, 'NA'),
     (19, 77, 'NA'),
     (20, 68, 'NA'),
     (21, 0.9, 'min'),
     (22, 8, 'NA'),
     (23, 40, 'NA'),
     (24, 90, 'NA'),
     (25, 92, 'NA'),
     (26, 130.4, 'max')]
    

    我想将每个值加总到“max”和每个值加总到“min”,并将这些结果附加到两个单独的列表中。

    例如,输出应为:

    min_sums = [1+2+3+4+5,11+12+13+14, 21+22+23+24+15]
    max_sums = [6+7+8+9+10, 15+16+17+18+19+20, 26]
    

    min_sums_lst = [[1,2,3,4,5], [11,12,13,14],[21,22,23,24,15]]
    max_sums_lst = [[6,7,8,9,10], [15,16,17,18,19,20], [26]]
    

    我想我可以使用索引值,但我对Python非常陌生,不确定如何继续。我正在学习生物学,但我相信学习计算机科学对我的工作有帮助。

    max_list = []
    min_list = []
    flag = ''
    min_index = 0
    max_index = float('inf');
    
    if flag == 'h':
        max_list.append(item)
    elif flag == 'c':
        min_list.append(item)
    
    for i, item in enumerate(minmax_list):
        print(i, item)
        print("max_index: ", max_index)
        print("min_index: ", min_index)
        if item[2] == 'min':
             min_index = i
             max_list('h', item[0])
        elif item[2] == 'NA' and (i < max_index):
            max_list('h', item[0])
        elif item[2] == 'max':
             max_index = i
             max_list('c', item[0])
        elif item[2] == 'NA' and (i > min_index):
            min_list('c', item[0])
    

    2 回复  |  直到 8 年前
        1
  •  1
  •   user8651755 user8651755    8 年前

    def partition_items(items):
        lists = {
            'min': [],
            'max': [],
        }
        current_kind = None
        current_list = None
        for value, _, kind in items:
            if kind != current_kind and kind != 'NA':
                current_kind = kind
                # You'll get a error here if current_kind isn't one of 'min'
                # or 'max'.
                current_list = lists[current_kind]
                current_list.append(0)
            # You'll get an error here if the first item in the list doesn't
            # have type of 'min' or 'max'.
            current_list[-1] += value
        return lists
    
    
    lists = partition_items(items)
    print(lists['min'])
    # -> [15, 50, 115]
    print(lists['max'])
    # -> [40, 105, 26]
    
        2
  •  1
  •   Stefan Pochmann    8 年前

    对不起,没有阅读你的尝试,看起来很复杂。

    min_sums = []
    max_sums = []
    for x, _, what in minmax_list:
        if what != 'NA':
            current = min_sums if what == 'min' else max_sums
            current.append(0)
        current[-1] += x