繁体   English   中英

如何在列表中分隔字符串的第一部分和最后一部分

[英]How to separate the first and last part of a string in a list

我有以下内容:

a = ['hello there good friend']

我需要以下内容:

a = ['hello', 'there good', 'friend']

基本上我需要它,所以列表的最后一个索引和第一个索引用逗号分隔,而两者之间的其余部分是单个字符串。 我已经尝试过为函数使用for循环,但是,它变得非常混乱,我认为这适得其反。

您实际上应该只使用split()函数将其split() ,然后对结果进行切片。 可能会有一些更简洁的方法,但是我能想到的最简单的方法是:

test = a[0].split()
result = [test[0], " ".join(test[1:-1]), test[-1]]

其中-1表示列表的最后一个条目。

您可以在一行中交替执行此操作(类似于inspectorG4dget的解决方案),但这意味着您将字符串拆分了三次,而不是一次。

[a[0].split()[0], " ".join(a[0].split()[1:-1]), a[0].split()[-1]]

或者,如果您认为切片比顶部稍微高一点(我这样做),则可以改用正则表达式,这可以说是比以上任何一种更好的解决方案:

import re
a = 'hello there good friend'
return re.split(' (.*) ', a)
>>> ['hello', 'there good', 'friend']

正如Ord所提到的,这个问题存在一些歧义,但是对于示例情况,这应该可以正常工作。

就性能而言,gnibbler是正确的,而regex实际上要慢两倍左右,并且两个操作的复杂度均为O(n) ,因此,如果性能是您的目标,那么最好选择他,但我仍然认为,正则表达式解决方案(对于正则表达式而言是难得的胜利)比其他解决方案更具可读性。 以下是直接计时结果:

# gnibbler's tuple solution
>>> timeit.timeit("s='hello there good friend';i1=s.find(' ');i2=s.rfind(' ');s[:i1], s[i1+1:i2], s[i2+1:]", number=100000)
0.0976870059967041

# gnibbler's list solution
>>> timeit.timeit("s='hello there good friend';i1=s.find(' ');i2=s.rfind(' ');[s[:i1], s[i1+1:i2], s[i2+1:]]", number=100000)
0.10682892799377441

# my first solution
>>> timeit.timeit("a='hello there good friend'.split();[a[0], ' '.join(a[1:-1]), a[-1]]", number=100000)
0.12330794334411621

# regex solution
>>> timeit.timeit("re.split(' (.*) ', 'hello there good friend')", "import re", number=100000)
0.27667903900146484
>>> [a[0].split(None, 1)[0]] + [a[0].split(None, 1)[-1].rsplit(None, 1)[0]] + [a[0].rsplit(None, 1)[-1]]
['hello', 'there good', 'friend']

最小化临时字符串的创建。

>>> a = ['hello there good friend']
>>> s = a[0]
>>> i1 = s.find(' ')
>>> i2 = s.rfind(' ')
>>> s[:i1], s[i1+1:i2], s[i2+1:]
('hello', 'there good', 'friend')     # as a tuple
>>> [s[:i1], s[i1+1:i2], s[i2+1:]]
['hello', 'there good', 'friend']     # as a list

暂无
暂无

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

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