我们说我有一个清单:
sentence = ['This','is','a','sentence']
我想在除第一个元素之外的每个元素前面添加一个空格。基本上,预期的结果是这样的:
sentence = ['This', ' is', ' a', ' sentence']
我试着这样做:
for word in sentence[1:]:
word = ' ' + word
但是,这个不会更改sentence
中的元素(为什么?)。
我可以写一些像这样丑陋的代码:
for i in range(1, len(sentence)):
sentence[i] = ' ' + sentence[i]
我认为这个会奏效,但这并不是一种优雅的方式......
最恐怖的方式是什么?
答案 0 :(得分:2)
这就是原地:
In [206]: sentence = ['This','is','a','sentence']
In [207]: for i,word in enumerate(sentence[1:],1):
.....: sentence[i] = ' '+word
.....:
In [208]: sentence
Out[208]: ['This', ' is', ' a', ' sentence']
这个方便的单行程不能就地执行:
In [209]: sentence = ['This','is','a','sentence']
In [210]: sentence = [sentence[0]] + [' '+word for word in sentence[1:]]
In [211]: sentence
Out[211]: ['This', ' is', ' a', ' sentence']