我想使用 python 動態連接串列中包含的字串,但我的邏輯遇到了錯誤。
目標是連接字串直到找到以數字開頭的字串,然后將此數字字串隔離到其自己的變數中,然后將剩余的字串隔離到第三個變數中。
例如:
stringList = ["One", "Two", "Three", "456", "Seven", "Eight", "Nine"]
resultOne = "OneTwoThree"
resultTwo = "456"
resultThree = "SevenEightNine"
這是我嘗試過的:
stringList = ["One", "Two", "Three", "456", "Seven", "Eight", "Nine"]
i = 0
stringOne = ""
stringTwo = ""
stringThree = ""
refStart = 1
for item in stringList:
if stringList[i].isdigit() == False:
stringOne = stringList[i]
i = 1
print(stringOne)
elif stringList[i].isdigit == True:
stringTwo = stringList[i]
i = 1
print(stringTwo)
refStart = i
else:
for stringList[refStart] in stringList:
stringThree = stringList[refStart]
refStart 1 = i
print(stringThree)
它出錯并顯示以下訊息:
File "c:\folder\Python\Scripts\test.py", line 19
refStart 1 = i
^
SyntaxError: 'operator' is an illegal expression for augmented assignment
uj5u.com熱心網友回復:
您可以使用itertools.groupby、理解和str.join:
stringList = ["One", "Two", "Three", "456", "Seven", "Eight", "Nine"]
from itertools import groupby
[''.join(g) for k,g in groupby(stringList, lambda x: x[0].isdigit())]
輸出:
['OneTwoThree', '456', 'SevenEightNine']
這個怎么運作:
groupby將對連續值進行分組,這里我對第一個字符進行了測驗來檢測它是否是數字。所以所有連續的字串都連接在一起。
如果格式更適合您,則作為字典:
dict(enumerate(''.join(g) for k,g in groupby(stringList,
lambda x: x[0].isdigit())))
輸出:
{0: 'OneTwoThree', 1: '456', 2: 'SevenEightNine'}
我不想加入連續的數字!
然后,您可以將上述內容與對組標識的測驗結合起來(如果字串以數字開頭,則為 True)并用于itertools.chain鏈接輸出:
stringList = ["One", "Two", "Three", "456", "789", "Seven", "Eight", "Nine"]
from itertools import groupby, chain
list(chain(*(list(g) if k else [''.join(g)]
for k,g in groupby(stringList, lambda x: x[0].isdigit()))))
輸出:
['OneTwoThree', '456', '789', 'SevenEightNine']
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/367461.html
下一篇:更簡潔的串列表示
