繁体   English   中英

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

[英]Slice every string in list in Python

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

这是我目前的清单:

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

这是我想要的结果列表:

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

我想从列表中的每个字符串中切掉最后两个字符。

我怎样才能做到这一点?

使用列表推导式创建一个新列表,将表达式的结果应用于输入列表中的每个元素; 这里是最后两个字符的[:-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']

你可以做:

>>> l = ['One', 'Two', 'Three', 'Four', 'Five'] 
>>> [i[:-2] for i in l]
['O', 'T', 'Thr', 'Fo', 'Fi']
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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM