简体   繁体   English

从字符串列表创建新的子字符串列表

[英]Create new list of substrings from list of strings

Is there an easy way in python of creating a list of substrings from a list of strings? python中是否有一种简单的方法可以从字符串列表中创建子字符串列表?

Example:例子:

original list: ['abcd','efgh','ijkl','mnop']原始列表: ['abcd','efgh','ijkl','mnop']

list of substrings: ['bc','fg','jk','no']子串列表: ['bc','fg','jk','no']

I know this could be achieved with a simple loop but is there an easier way in python (Maybe a one-liner)?我知道这可以通过一个简单的循环来实现,但是在 python 中是否有更简单的方法(也许是单行)?

Use slicing and list comprehension :使用slicinglist comprehension

>>> lis = ['abcd','efgh','ijkl','mnop']
>>> [ x[1:3] for x in lis]
['bc', 'fg', 'jk', 'no']

Slicing:切片:

>>> s = 'abcd'
>>> s[1:3]      #return sub-string from 1 to 2th index (3 in not inclusive)
'bc'

With a mix of slicing and list comprehensions you can do it like this结合切片和列表理解,你可以这样做

listy = ['abcd','efgh','ijkl','mnop']
[item[1:3] for item in listy]
>> ['bc', 'fg', 'jk', 'no']

You can use a one-liner list-comprehension .您可以使用单行列表理解

Using slicing , and relative positions, you can then trim the first and last character in each item.使用切片和相对位置,您可以修剪每个项目中的第一个和最后一个字符。

>>> l = ['abcd','efgh','ijkl','mnop']
>>> [x[1:-1] for x in l]
['bc', 'fg', 'jk', 'no']

If you are doing this many times, consider using a function:如果您多次这样做,请考虑使用一个函数:

def trim(string, trim_left=1, trim_right=1):
    return string[trim_left:-trim_right]

def trim_list(lst, trim_left=1, trim_right=1):
    return [trim(x, trim_left, trim_right) for x in lst] 

>>> trim_list(['abcd','efgh','ijkl','mnop'])
['bc', 'fg', 'jk', 'no']

如果你想在一行中做到这一点,你可以试试这个:

>>> map(lambda s: s[1:-1], ['abcd','efgh','ijkl','mnop'])

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

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