How to flatten only one sub list of list of lists

Jussi Piitulainen jussi.piitulainen at helsinki.fi
Wed Mar 1 02:19:59 EST 2017


Sayth Renshaw writes:

> How can I flatten just a specific sublist of each list in a list of lists?
>
> So if I had this data
>
>
> [   ['46295', 'Montauk', '3', '60', '85', ['19', '5', '1', '0 $277790.00']],
>     ['46295', 'Dark Eyes', '5', '59', '83', ['6', '4', '1', '0 $105625.00']],
>     ['46295', 'Machinegun Jubs', '6', '53', '77', ['6', '2', '1', '1 $71685.00']],
>     ['46295', 'Zara Bay', '1', '53', '77', ['12', '2', '3', '3 $112645.00']]]
>
>
> How can I make it be
>
>
> [   ['46295', 'Montauk', '3', '60', '85', '19', '5', '1', '0 $277790.00'],
>     ['46295', 'Dark Eyes', '5', '59', '83', '6', '4', '1', '0 $105625.00'],
>     ['46295', 'Machinegun Jubs', '6', '53', '77', '6', '2', '1', '1 $71685.00'],
>     ['46295', 'Zara Bay', '1', '53', '77', '12', '2', '3', '3 $112645.00']]

Here's two ways. First makes a copy, second flattens each list in place,
both assume it's the last member (at index -1) of the list that needs
flattening.

datami = [   ['46295', 'Montauk', '3', '60', '85', ['19', '5', '1', '0 $277790.00']],
             ['46295', 'Dark Eyes', '5', '59', '83', ['6', '4', '1', '0 $105625.00']],
             ['46295', 'Machinegun Jubs', '6', '53', '77', ['6', '2', '1', '1 $71685.00']],
             ['46295', 'Zara Bay', '1', '53', '77', ['12', '2', '3', '3 $112645.00']]]

flat = [ data[:-1] + data[-1] for data in datami ]

for data in datami: data.extend(data.pop())

print('flat copy of datami:', *flat, sep = '\n')
print('flattened datami:', *datami, sep = '\n')


More information about the Python-list mailing list