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