简体   繁体   English

将 Python 列表项分解为较小的列表,替换新的子列表项,并将列表与新值重新组合在一起

[英]Break Python list item down into smaller list, replace new sub list item, and put list back together with new value

I'm not sure how to do this, so apologies for any confusion.我不知道该怎么做,所以对任何混淆表示歉意。

I would like to take a list containing sentences, and break the sentences down into a smaller sub list.我想获取一个包含句子的列表,并将句子分解为一个较小的子列表。

Somehow, I was hoping to replace an item in new sub list, and return the list back with it's new value.不知何故,我希望替换新子列表中的一个项目,并用它的新值返回列表。

For example:例如:

txt_lst = ['That is Jays sock.', 'It is green.', 'Leave it there.']

Then I want to take txt_lst[0] , and make a new sub_txt_lst:然后我想取txt_lst[0] ,并制作一个新的 sub_txt_lst:

sub_txt_lst = ['That', 'is', 'Jays', 'sock.']

And replace the item sub_txt_lst[2] with her .并将项目sub_txt_lst[2]替换为her

Afterwards, I would like txt_lst to read:之后,我希望txt_lst阅读:

txt_lst = ['That is her sock.', 'It is green.', 'Leave it there.']

Again, sorry if this explanation is poorly written.再次抱歉,如果这个解释写得不好。

You can use re to do this in an efficient way:您可以使用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.']

Here ya go:这里是 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)

Or if you'd like to just modify a specific word:或者,如果您只想修改特定单词:

txt_lst[0] = txt_lst[0].replace("Jays","her")

Both yield:两者都产生:

['That is her sock.', 'It is green.', 'Leave it there.']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM