How to flatten only one sub list of list of lists
Sayth Renshaw
flebber.crue at gmail.com
Wed Mar 1 03:14:46 EST 2017
> Replace the slice row[index:index+1] with row[index], either by building a new list or in place:
>
> >>> def show(data):
> ... for item in data: print(item)
> ...
> >>> def flatten_one(rows, index):
> ... return [r[:index] + r[index] + r[index+1:] for r in rows]
> ...
> >>> def flatten_inplace(rows, index):
> ... for row in rows:
> ... row[index:index+1] = row[index]
> ...
> >>> flatten_inplace(data, 5)
> >>> show(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']
I went for the one I can understand which was inplace
def flatten_inplace(rows, index):
for row in rows:
row[index:index + 1] = row[index]
return rows
See now if I can make it more adaptable to use it in some other situations, quite useful.
Thanks
Sayth
More information about the Python-list
mailing list