How to flatten only one sub list of list of lists

Robert L. No_spamming at noWhere_7073.org
Sat Apr 1 16:22:59 EDT 2017


On 3/1/2017, Sayth Renshaw wrote:

> 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']]
> 
> Been looking around but most solutions just entirely flatten everything.
> This was popular on SO but yeah it flattens everything  I want to be more selective
> 
> def flatten(lst):
>     for elem in lst:
>         if type(elem) in (tuple, list):
>             for i in flatten(elem):
>                 yield i
>         else:
>             yield elem
> 

[['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']]].
map( &:flatten )

 ===>
[["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"]]

-- 
[T]he driving force behind mass immigration is the organized Jewish community,
which feels its interests are best served by a "diverse" society divided
between antagonistic groups that can be easily dominated by their cohesive and
privileged tribe.
http://www.renseradioarchives.com/dduke/



More information about the Python-list mailing list