簡體   English   中英

將 Python 列表項分解為較小的列表,替換新的子列表項,並將列表與新值重新組合在一起

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM