我有一个像'这样的字符串....(((...((...'我必须为此生成另一个字符串'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方式完成itertools.groupby。请注意,我不确定是否'h2'
在你的预期输出中是一个拼写错误或者如果它应该是'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)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)