[Python] Efficient way to replace list elements with COMPUTED values

Discussão em 'Python' iniciado por Stack, Maio 21, 2025.

  1. Stack

    Stack Membro Participativo

    Consider a 2d python list (ie: lst2) and a matrix that gives the value of each adjacent pair of letters (ie: value_matrix).

    lst2 = [['acba', 'ca'], ['babab', 'ca', 'bc']]

    value_matrix = [['aa', 0], ['ab', 3], ['ac', 5], ['ba', 2], ['bb', 0], ['bc', 9], ['ca', 7], ['cb', 4], ['cc', 0]]


    I want to replace each element of lst2 with an integer derived by summing the values of its adjacent pairs. For example, 'acba' sums the values 5 (from 'ac') + 4 (from 'cb' + 2 (from 'ba') = 11. I'm sure a dictionary can be used, but I don't know how to incorporate the summing of adjacent pair values.

    When completed, the result should be:

    new_lst2 = [[11, 7], [10, 7, 9]]

    Continue reading...

Compartilhe esta Página