2017-10-21 134 views
0

注意:我編輯了這個問題!Python的總和值列表中的元組達到特定值

我在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來說很新,我不太確定如何繼續。我正在學習生物學,但我相信學習CS可以幫助我的工作。

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]) 

我對Python很新穎 - 任何幫助將不勝感激。我只是試圖在上面輸出中指出的基於最小值和最大值的每個元組中添加第一項。

+0

我仍然有如何跟蹤值其實我總結的問題,因此,如果任何人都可以瞭解如何獲得min_sums_lst和max_sums_lst加上,這將有很大的幫助! – djennacs

回答

1

我的答案與@斯蒂芬的方法略有不同。它做了更多的驗證,除了'min'和'max'之外,你可以很容易地添加其他類型。

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] 
1

對不起,沒有打擾讀你的嘗試,看起來很複雜。

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 
+0

謝謝你的答案 - 這看起來是正確的,但我試圖擴大它,讓你的策略更有意義! – djennacs