python - 在任意索引处有效地划分字符串

标签 python string python-3.x idioms

<分区>

给定一个任意字符串(即不基于模式),说:

>>> string.ascii_letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'

我正在尝试根据索引列表对字符串进行分区。

这是我尝试过的,确实有效:

import string

def split_at_idx(txt, idx):
    new_li=[None]*2*len(idx)
    new_li[0::2]=idx
    new_li[1::2]=[e for e in idx]
    new_li=[0]+new_li+[len(txt)]
    new_li=[new_li[i:i+2] for i in range(0,len(new_li),2)]  
    print(new_li)
    return [txt[st:end] for st, end in new_li]

print(split_at_idx(string.ascii_letters, [3,10,12,40]))  
# ['abc', 'defghij', 'kl', 'mnopqrstuvwxyzABCDEFGHIJKLMN', 'OPQRSTUVWXYZ']

拆分基于索引列表 [3,10,12,40]。然后需要将该列表转换为开始、结束对列表,例如 [[0, 3], [3, 10], [10, 12], [12, 40], [40, 52]] 。我使用切片赋值来设置偶数和赔率,然后使用列表理解来分组成对,然后使用第二个 LC 来返回分区。

对于这样一个简单的函数来说,这似乎有点复杂。有没有更好/更有效/更惯用的方法来做到这一点?

最佳答案

我感觉最近有人问过这个问题,但我现在找不到了。假设掉落的字母是意外,你不能这样做:

def split_at_idx(s, idx):
    return [s[i:j] for i,j in zip([0]+idx, idx+[None])]

之后我们有

>>> split_at_idx(string.ascii_letters, [3, 10, 12, 40])
['abc', 'defghij', 'kl', 'mnopqrstuvwxyzABCDEFGHIJKLMN', 'OPQRSTUVWXYZ']
>>> split_at_idx(string.ascii_letters, [])
['abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ']
>>> split_at_idx(string.ascii_letters, [13, 26, 39])
['abcdefghijklm', 'nopqrstuvwxyz', 'ABCDEFGHIJKLM', 'NOPQRSTUVWXYZ']

关于python - 在任意索引处有效地划分字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20696084/

相关文章:

python - NOT NULL 约束失败 Django CreateView

python - SQLAlchemy - 错误 TVP 的行必须是 Sequence 对象

string - DAWG/DAFSA 中的元信息

python - 如何在UML中绘制类的元类?

c# - 到处查找枚举转换为字符串

c++ - 当getline()读取的行大于系统内存时会发生什么?

python - 嵌套单行循环

python - 在 Windows 上安装 pyquery

python - np.random.choice 在直方图中有一个缺口

python - 如何对 pandas 中两个不同大小的数据集的列求和