用定界符分割字符串的可能情况

时间:2019-07-09 22:20:25

标签: python string list split permutation

我有一个字符串:str = "**Quote_Policy_Generalparty_NameInfo** "

我将字符串拆分为str.split("_"),这为我提供了python列表。

感谢您提供以下任何帮助以获取输出。

[ Quote, Quote_Policy, Quote_Policy_Generalparty, Quote_Policy_Generalparty_NameInfo ]

4 个答案:

答案 0 :(得分:3)

您可以使用range(len(list))创建切片list[:1]list[:2]等,然后使用"_".join(...)连接每个切片

text = "Quote_Policy_Generalparty_NameInfo "
data = text.split('_')

result = []

for x in range(len(data)):
    part = data[:x+1]
    part = "_".join(part)
    result.append(part)

print(result)

答案 1 :(得分:2)

destio = io.bytesIO()
with tarfile.open(fileobj=a, mode="r:gz") as t1, \
        tarfile.open(fileobj=b, mode="r:gz") as t2, \
        tarfile.open(fileobj=destio, mode="w:gz") as dest:

    t1_members = [m for m in t1.getmembers()]
    t1_names = t1.getnames()
    t2_members = [m for m in t2.getmembers() if m.name not in t1_names]

    for member in t1_members:
        if member.isdir():
            dest.addfile(member)
        else:
            dest.addfile(member, t1.extractfile(member))

    for member in t2_members:
        if member.isdir():
            dest.addfile(member)
        else:
            dest.addfile(member, t2.extractfile(member))

上面input = "Quote_Policy_Generalparty_NameInfo" tokenized = input.split("_") combined = [ "_".join(tokenized[:i]) for i, token in enumerate(tokenized, 1) ] 的值为

combined

答案 2 :(得分:0)

您可以使用accumulate中的itertools,基本上我们再给它一个参数,它决定了如何累加两个元素

from itertools import accumulate
input = "Quote_Policy_Generalparty_NameInfo"
output = [*accumulate(input.split('_'), lambda str1, str2 : '_'.join([str1,str2])),]

给出:

Out[11]: 
['Quote',
 'Quote_Policy',
 'Quote_Policy_Generalparty',
 'Quote_Policy_Generalparty_NameInfo']

答案 3 :(得分:0)

如果您发现以上答案过于清晰和令人满意,则还可以考虑使用正则表达式:

>>> import regex as re  # For `overlapped` support
>>> x = "Quote_Policy_Generalparty_NameInfo"
>>> list(map(lambda s: s[::-1], re.findall('(?<=_).*$', '_' + x[::-1], overlapped=True)))
['Quote_Policy_Generalparty_NameInfo', 'Quote_Policy_Generalparty', 'Quote_Policy', 'Quote']