我有一個字串:
s = """YES string1 string2 YES string3 string4 string5 YES string6 NO String7 NO string8 string9 YES string10 string11"""
我需要這樣的輸出:
wanted_output = {
"YES": [
"string1 string2",
"string3 string4 string5",
"string6",
"string10 string11",
],
"NO" : ["String7", "string8 string9"]
}
我有為此作業的功能,但對我來說它看起來并不優雅。你知道更優雅的解決方法嗎?
def convert(text):
words = text.split()
yes = "YES"
no = "NO"
yes_list = []
no_list = []
current = ""
for word in words:
if word == yes:
current = yes
yes_list.append("|")
continue
if word == no:
current = no
no_list.append("|")
continue
if current == yes:
yes_list.append(word)
elif current == no:
no_list.append(word)
yes_str = " ".join(yes_list)
no_str = " ".join(no_list)
yes_list = yes_str.split("|")
no_list = no_str.split("|")
yes_list = [yes_str.strip() for yes_str in yes_list if yes_str]
no_list = [no_str.strip() for no_str in no_list if no_str]
return {"YES": yes_list, "NO": no_list}
uj5u.com熱心網友回復:
用字符替換是和否(確保它不會出現在文本中),然后拆分。
s = """YES string1 string2 YES string3 string4 string5 YES string6 NO String7 NO string8 string9 YES string10 string11"""
def convert(text):
data = s.replace('YES', '*YES*').replace('NO', '*NO*').split('*')
data_strip = [i.strip() for i in data if i.strip()]
yes_list = []
no_list = []
for ind, val in enumerate(data_strip):
if 'YES' in val:
yes_list.append(data_strip[ind 1])
if 'NO' in val:
no_list.append(data_strip[ind 1])
return {"YES": yes_list, "NO": no_list}
print(convert(s))
>>> {'YES': ['string1 string2', 'string3 string4 string5', 'string6', 'string10 string11'], 'NO': ['String7', 'string8 string9']}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/516513.html
標籤:Python细绳
