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

标签 python string list

我有以下内容:

a = ['hello there good friend']

我需要以下内容:

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

基本上我需要它,所以列表的最后一个索引和第一个索引用逗号分隔,而中间的其余部分是一个字符串。我已经尝试为我的函数使用 for 循环,但是,它只是变成了一些非常困惑的东西,我认为这会适得其反。

最佳答案

您实际上应该使用 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 是对的,正则表达式实际上慢了大约两倍,而且这两个操作的复杂度都是 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

关于python - 如何分隔列表中字符串的第一部分和最后一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20461470/

相关文章:

python - python除以负数的问题

python - 如何使用 Python 的 CFFI 传递指向 C 函数的指针?

PHP 字符串到 hashmap

c - 在二维数组中搜索元素,C 编程

python - 我可以快速获得 python 列表中最内部子列表的最小长度吗?

python - 将数字追加到列表的指定元素中

python - 防止分组条形图中的标签重叠

python - Py2exe - Pmw WindowsError : [Error 3]

c - strtok 似乎删除了字符串部分 - 我使用它正确吗?

c - 如何在C中读取一行中的多个字符串,每个字符串都包含空格?