[英]Break Python list item down into smaller list, replace new sub list item, and put list back together with new value
我不知道該怎么做,所以對任何混淆表示歉意。
我想獲取一個包含句子的列表,並將句子分解為一個較小的子列表。
不知何故,我希望替換新子列表中的一個項目,並用它的新值返回列表。
例如:
txt_lst = ['That is Jays sock.', 'It is green.', 'Leave it there.']
然后我想取txt_lst[0]
,並制作一個新的 sub_txt_lst:
sub_txt_lst = ['That', 'is', 'Jays', 'sock.']
並將項目sub_txt_lst[2]
替換為her
。
之后,我希望txt_lst
閱讀:
txt_lst = ['That is her sock.', 'It is green.', 'Leave it there.']
再次抱歉,如果這個解釋寫得不好。
您可以使用re
以有效的方式執行此操作:
import re
txt_lst = ['That is Jays sock.', 'It is green.', 'Leave it there.']
print([re.sub(r'\bJays\b', 'her', x) for x in txt_lst])
# ['That is her sock.', 'It is green.', 'Leave it there.']
這里是 go:
txt_lst = ['That is Jays sock.', 'It is green.', 'Leave it there.']
sub_txt_lst = txt_lst[0].split()
sub_txt_lst[2] = "her"
txt_lst[0] = " ".join(sub_txt_lst)
或者,如果您只想修改特定單詞:
txt_lst[0] = txt_lst[0].replace("Jays","her")
兩者都產生:
['That is her sock.', 'It is green.', 'Leave it there.']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.