生成序列的字符数统计

3
我有一个字符串,如'....(((...((...',我需要生成另一个字符串'ss(4)h5(3)ss(3)h2(2)ss(3)'。

'.'代表'ss',连续的'.'数量在括号中。

'('代表'h5',连续的'('数量在括号中。

目前,我能得到输出'ss(4)h5(3)ss(3)',我的代码忽略了最后两个字符序列。这是我迄今为止所做的。

def main():
    stringInput = raw_input("Enter the string:")
    ssCount = 0
    h5Count = 0
    finalString = ""
    ssString = ""
    h5String = ""
    ssCont = True
    h5Cont = True
    for i in range(0, len(stringInput), 1):
        if stringInput[i] == ".":
            h5Cont = False
            if ssCont:
                ssCount = ssCount + 1
                ssString = "ss(" + str(ssCount) + ")"
                ssCont = True
            else:
                finalString = finalString + ssString
                ssCont = True
                ssCount = 1
        elif stringInput[i] == "(":
            ssCont = False
            if h5Cont:
                h5Count = h5Count + 1
                h5String = "h5(" + str(h5Count) + ")"
                h5Cont = True
            else:
                finalString = finalString + h5String
                h5Cont = True
                h5Count = 1

    print finalString
main()

如何修改代码以获得所需的输出?


很不错的努力 - 我可以问一下,你是因为这是某种任务而被困在这种方法上了吗?还是你愿意尝试其他更符合Python风格的选项? - Jon Clements
@JonClements 我对任何符合Python语言习惯的选项都持开放态度。我只是想获得所需的输出。 - coderSree
2个回答

4

我不确定如何修改您现有的代码,但是在我看来,可以使用itertools.groupby非常简洁和Pythonic地完成此操作。请注意,我不确定您期望输出中的'h2'是否是一个错别字,还是应该是'h5',我假设它是'h5'

from itertools import chain, groupby

string = '....(((...((...'

def character_count(S, labels): # this allows you to customize the labels you want to use
    for K, G in groupby(S):
        yield labels[K], '(', str(sum(1 for c in G)), ')' # sum() counts the number of items in the iterator G

output = ''.join(chain.from_iterable(character_count(string, {'.': 'ss', '(': 'h5'}))) # joins the components into a single string
print(output)

# >>> ss(4)h5(3)ss(3)h5(2)ss(3)

谢谢。这正是我所需要的! :) - coderSree

1

@Kelvin的回答很好,但是如果你想自己定义一个函数,你可以这样做:

def h5ss(x):
    names = {".": "ss", "(": "h5"}
    count = 0
    current = None
    out = ""
    for i in x:
        if i == current:
            count += 1
        else:
            if current is not None:
                out += "{}({})".format(names[current], count)
            count = 1
            current = i
    if current is not None:
        out += "{}({})".format(names[current], count)
    return out

工作得很好,真的很有帮助。谢谢 :) - coderSree
@user5861486 没问题。顺便说一下,你代码中的问题是,你应该直接将“ss”和“h5”的字符串添加到输出中,而不仅仅是在下一个序列完成时才添加。这就是为什么最后两个缺失的原因。 - CodenameLambda

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接