私信  •  关注

MrCed

MrCed 最近创建的主题
MrCed 最近回复了
6 年前
回复了 MrCed 创建的主题 » 使用python的列表中元素的总和

如果“根”总是相同的,你可以用正则表达式来捕获它们。

有了这个解决方案 更改原始列表 .

import re

l = [(0.14409883378622257, 'count_90'), 
     (0.1274820635854658, 'count_60'), 
     (0.10362930186446877, 'count_30'), 
     (0.017066033814948037, 'country_code_destination_ID'),
     (0.014104260612047153, 'country_code_destination_US'),     
     (0.011414953372550486, 'SACC_MARKET_SEGMENT_BDZ'),  
     (0.010291762087645236, 'leading_bu_PP'), 
     (0.009979426898654558, 'SACC_MARKET_SEGMENT_IT3')]

country_code_value = 0
sacc_market_value = 0

# Loop on the list with indexes and increment values when catch regex pattern.
for i, t in enumerate(l):
    if re.search(r"country_code_destination", t[1]):
        # remove the element of the list and keep value in variable      
        country_code_value += l.pop(i)[0]       
    elif re.search(r"SACC_MARKET_SEGMENT", t[1]):
        # remove the element of the list and keep value in variable
        sacc_market_value += l.pop(i)[0]

# Make tuples
country_code_destination = (country_code_value, "country_code_destination")
sacc_market_segment = (sacc_market_value, "SACC_MARKET_SEGMENT")

# And append to the original list
l.append(country_code_destination)
l.append(sacc_market_segment)