将所有字符串切成列表? [英] Slice all strings in a list?
问题描述
是否有Python方式将列表中的所有字符串切片?
Is there a Pythonic way to slice all strings in a list?
假设我有一个字符串列表:
Suppose I have a list of strings:
list = ['foo', 'bar', 'baz']
我只想要每个字符串的最后2个字符:
And I want just the last 2 characters from each string:
list2 = ['oo', 'ar', 'az']
我该怎么办?
我知道我可以遍历列表并从每个列表中提取list[i][-2:]
,但这似乎不是Python风格的.
I know I can iterate thru the list and take list[i][-2:]
from each one, but that doesn't seem very Pythonic.
一般来说,我的代码是:
Less generally, my code is:
def parseIt(filename):
with open(filename) as f:
lines = f.readlines()
result = [i.split(',') for i in lines[]]
...除了我只想从每行(而不是整行)中拆分lines[i][20:]
.
...except I only want to split lines[i][20:]
from each line (not the whole line).
推荐答案
您提到您可以按照规范进行list[i][-2:]
转换列表,但是您真正要寻找的是:
You mentioned that you can do list[i][-2:]
for transforming the list per your specification, but what you are actually looking for is:
[word[1:] for word in lst]
此外,对于您提供的代码示例,您希望从一开始就将其分割为20个字符,解决方案将是相同的:
Furthermore, for the code sample you provided where you are looking to slice 20 characters from the beginning, the solution would be the same:
result = [i[20:].split(',') for i in lines]
这篇关于将所有字符串切成列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!