[Python] How do you use list comprehensions in Python for sum of squares in a list?

Discussão em 'Python' iniciado por Stack, Março 11, 2025.

  1. Stack

    Stack Membro Participativo

    This is the data provided.

    # Data on probability of expansion success by country estimates
    success_estimates = {
    'Australia': [0.6, 0.33, 0.11, 0.14],
    'France': [0.66, 0.78, 0.98, 0.2],
    'Italy': [0.6],
    'Brazil': [0.22, 0.22, 0.43],
    'USA': [0.2, 0.5, 0.3],
    'England': [0.45],
    'Canada': [0.25, 0.3],
    'Argentina': [0.22],
    'Greece': [0.45, 0.66, 0.75, 0.99, 0.15, 0.66],
    'Morocco': [0.29],
    'Tunisia': [0.68, 0.56],
    'Egypt': [0.99],
    'Jamaica': [0.61, 0.65, 0.71],
    'Switzerland': [0.73, 0.86, 0.84, 0.51, 0.99],
    'Germany': [0.45, 0.49, 0.36]
    }


    This is the practice question and a copy of my closest, but non-successful code.

    Using list comprehensions, write a script to create a list of lists called sum_squares_list, where each element of the list is a two-item list [country name, value]. The value item in the list should be the sum of squares of that country's success estimates. For example, one element of sum_squares_list should be for Jamaica, where the two-item list is [Jamaica, 1.2987] (since 1.2987 = 0.61^2 + 0.65^2 + 0.71^2).

    My Closest but Incorrect Code

    sum_squares_list = [[i, sum(success_estimates)] for i in success_estimates]
    sum_squares_list

    [['Australia', 1.1800000000000002],
    ['France', 2.62],
    ['Italy', 0.6],
    ['Brazil', 0.87],
    ['USA', 1.0],
    ['England', 0.45],
    ['Canada', 0.55],
    ['Argentina', 0.22],
    ['Greece', 3.66],
    ['Morocco', 0.29],
    ['Tunisia', 1.2400000000000002],
    ['Egypt', 0.99],
    ['Jamaica', 1.97],
    ['Switzerland', 3.9299999999999997],
    ['Germany', 1.2999999999999998]]


    I am having lots of trouble trying to find the sum of squares. Summing all those values is easy enough, but how do I square the elements before I sum it?

    Continue reading...

Compartilhe esta Página