在列表的元素中添加空格 [英] Add spaces to elements of list
问题描述
我已经为此苦苦挣扎了一段时间.我有一个带有子列表的列表,我想在子列表的每个元素之前添加一个空格.例如:
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]]
结果应该是:
lin = [[' ',2], [' ',3], [' ',2], [' ',2, ' ',2], [' ',2]]
我试图做到这一点:
for a in lin:
for e in a:
e = (' ') , e
但是我获得了完全相同的列表,没有任何改动
but I obtained exactly the same list with no alterations
推荐答案
我认为您实际上的意思是类似Tigerhawk的评论.
I assume that you actually meant something like the comment of Tigerhawk.
您的问题是e= (' ') , e
只是将e
的值(原来是嵌套列表中的每个值)覆盖为包含空格和原始值的元组.这实际上并不会更改列表中的任何内容,只会更改e
最初指向的内容.
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]]
请注意内部循环:for i in range(len(a)-1,-1,-1):
之所以这样做是出于两个原因:
Note the inner loop: for i in range(len(a)-1,-1,-1):
This is done this way because of 2 reasons:
- 您不想实际遍历
a
,因为您将要更改a
中的值 - 您需要从最高索引开始,因为如果从0开始,则其前面其余项目的索引将发生变化.
- you dont want to be actually looping through
a
since you are going to be changin the values ina
- 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.
这篇关于在列表的元素中添加空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!