我正在解決 codewars 中的一個問題,但我被困在了一個步驟上
我有一個這樣的字串defr[fr]i##abde[fgh]ijk ,我想在元素之間添加分隔符,但括號內的元素應該是這種情況,所以輸出應該是[d,e,f,r,[fr],i,#,#,a,b,d,e,[fgh],i,j,k]
我試過用不同的條件回圈,
我想出了這個代碼
if land[i] == "[":
print(land[i])
j = i 1
while land[j] != "]":
print(land[j])
j =1
else:
number_of_shelter.append(land[i:j 1])
else:
continue
但它只附加括號中的元素
有人可以告訴我如何將其他元素與括號中的元素一起附加的方法
其他示例:
##[a]b[c]#>>>[#,#,[a],b,[c],#]
[a]#[b]#[c] >>>
[[a],#,[b],#,[c]]
uj5u.com熱心網友回復:
這有效:
def foo(s):
output = ""
inBracket = False
for i in s:
if i == "[" or (inBracket == True and i != "]"):
output = i
inBracket = True
else:
inBracket = False
output = i ","
if output[len(output)] == ",":
output = output[:-1]
return output
uj5u.com熱心網友回復:
這是作業代碼
str = "defr[fr]i##abde[fgh]ijk"
arr = []
in_the_bracket = False
for i in str:
if i == '[':
in_the_bracket = True
chr = ''
if in_the_bracket:
chr = chr i
else:
arr.append(i)
if i == ']':
in_the_bracket = False
arr.append(chr)
print(arr)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/399271.html
上一篇:獲取串列中的元素范圍并交換
下一篇:獲取單個串列的遞回排列
