问题
Is there a Pythonic way to slice all strings in a list?
Suppose I have a list of strings:
list = ['foo', 'bar', 'baz']
And I want just the last 2 characters from each string:
list2 = ['oo', 'ar', 'az']
How can I get that?
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[]]
...except I only want to split lines[i][20:]
from each line (not the whole line).
回答1:
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]
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]
来源:https://stackoverflow.com/questions/39908314/slice-all-strings-in-a-list