Add spaces to elements of list

2019-09-11 19:16发布

I've been struggling for a while with this. I have a list with sublist and I wanted to add an element that is a space before each element of the sublists. for example:

lin = [[2], [3], [2], [2, 2], [2]]

the result should be:

lin = [[' ',2], [' ',3], [' ',2], [' ',2, ' ',2], [' ',2]]

I've tried to do this:

for a in lin:
    for e in a:
        e = (' ') , e 

but I obtained exactly the same list with no alterations

3条回答
贼婆χ
2楼-- · 2019-09-11 20:02

A neat, functional solution, that uses only built-in functions

lin = [[2], [3], [2], [2, 2], [2]]

add_spaces = lambda l: [i for x in zip(' '*len(l), l) for i in x]
new_list = [add_spaces(l) for l in lin]

Output:

>>> print new_list
[[' ', 2], [' ', 3], [' ', 2], [' ', 2, ' ', 2], [' ', 2]]
查看更多
贪生不怕死
3楼-- · 2019-09-11 20:07

I assume that you actually meant something like the comment of Tigerhawk.

Your problem is that e= (' ') , e is just overwriting the value of e (which was originally each value in your nested list) to a tuple containing a space and the original value. This doesnt actually change anything inside of your list, just changes whatever it is that e was originally pointing to.

You can instead do something like this:

>>> lin = [[2], [3], [2], [2, 2], [2]]
>>> for a in lin:
        for i in range(len(a)-1,-1,-1):
            a.insert(i, ' ')


>>> lin
[[' ', 2], [' ', 3], [' ', 2], [' ', 2, ' ', 2], [' ', 2]]

Note the inner loop: for i in range(len(a)-1,-1,-1): This is done this way because of 2 reasons:

  1. you dont want to be actually looping through a since you are going to be changin the values in a
  2. You need to start with the highest index because if you start from 0, the indexes of the rest of the items ahead of it will change.
查看更多
孤傲高冷的网名
4楼-- · 2019-09-11 20:17

You can use list comprehension and chain.from_iterable from itertools

>>> from itertools import chain
>>> lin = [[2], [3], [2], [2, 2], [2]]
>>> [list(chain.from_iterable([(' ', i) for i in j])) for j in lin]
[[' ', 2], [' ', 3], [' ', 2], [' ', 2, ' ', 2], [' ', 2]]
>>> 
查看更多
登录 后发表回答