在Python中切片列表中的每个字符串

6

我希望在Python中对列表中的每个字符串进行切片。

这是我的当前列表:

['One', 'Two', 'Three', 'Four', 'Five']

这是我期望的结果列表:

['O', 'T', 'Thr', 'Fo', 'Fi']

我想从我的列表中的每个字符串中切掉最后两个字符。
我该怎么做?

4
在寻求解决方案之前,请尝试展示最小的努力。 - Maroun
你能从一个字符串中切掉最后两个字符吗? - Peter Wood
2
我认为我们应该通过不提供现成的解决方案来阻止这种问题,这样做并不能真正帮助提问者,至少对他的未来没有好处。 - Maroun
3个回答

14
使用列表推导式创建一个新列表,其中包含应用于输入列表中每个元素的表达式的结果;这里是最后两个字符的[:-2]切片,返回余数。
[w[:-2] for w in list_of_words]

演示:
>>> list_of_words = ['One', 'Two', 'Three', 'Four', 'Five']
>>> [w[:-2] for w in list_of_words]
['O', 'T', 'Thr', 'Fo', 'Fi']

3

您可以做以下事情:

>>> l = ['One', 'Two', 'Three', 'Four', 'Five'] 
>>> [i[:-2] for i in l]
['O', 'T', 'Thr', 'Fo', 'Fi']

2
x=['One', 'Two', 'Three', 'Four', 'Five']
print map(lambda i:i[:-2],x)  #for python 2.7
print list(map(lambda i:i[:-2],x)) #for python 3

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接