为了账号安全,请及时绑定邮箱和手机立即绑定

替换列表中的单词并附加到同一列表中

替换列表中的单词并附加到同一列表中

叮当猫咪 2021-05-30 14:06:23
我的列表:city=['Venango Municiplaity', 'Waterford ship','New York']预期结果:city = ['Venango Municiplaity ', 'Waterford ship','New York','Venango','Waterford']常用的词:common_words = ['ship','municipality']扫描我的列表中的所有项目,去掉常用词并重新插入到同一个列表中,如预期结果所示。我能够搜索包含常用词的项目,但不确定如何将其替换为空白并重新插入“我的列表”中。到目前为止我的代码:for item in city:    if(any(x in s.lower() for s in item.split(' ') for x in common_words)) :
查看完整描述

3 回答

?
神不在的星期二

TA贡献1963条经验 获得超6个赞

我建议您使用以下解决方案,使用re.subwithflags=re.IGNORECASE去除忽略大小写的常用词:


import re


city = ['Venango Municipality', 'Waterford ship','New York']

common_words = ['ship','municipality']


toAppend = []


for c in city:

    for cw in common_words:

        if cw.lower() in c.lower().split():

            toAppend.append(re.sub(cw, "", c, flags=re.IGNORECASE).strip())


city += toAppend


print(city) # ['Venango Municipality', 'Waterford ship', 'New York', 'Venango', 'Waterford']

这是一个使用列表理解的单线样式解决方案,虽然简短,但可读性较差:


import re


city = ['Venango Municipality', 'Waterford ship','New York']

common_words = ['ship','municipality']


city += [re.sub(cw, "", c, flags=re.IGNORECASE).strip() for c in city for cw in common_words if cw.lower() in c.lower().split()]


print(city) # ['Venango Municipality', 'Waterford ship', 'New York', 'Venango', 'Waterford']



查看完整回答
反对 回复 2021-06-01
?
四季花海

TA贡献1811条经验 获得超5个赞

您可以尝试一下,创建新列表以保存数据,应将数据添加到原始列表中,然后合并结果:


In [1]: city=['Venango Municiplaity', 'Waterford ship','New York']


In [2]: common_words = ['ship', 'municiplaity']


In [3]: list_add = []


In [4]: for item in city:

   ...:     item_words = [s.lower() for s in item.split(' ')]

   ...:     if set(common_words) & set(item_words):

   ...:         new_item = [s for s in item.split(' ') if s.lower() not in common_words]

   ...:         list_add.append(" ".join(new_item))

   ...:         


In [5]: city + list_add

Out[5]: ['Venango Municiplaity', 'Waterford ship', 'New York', 'Venango', 'Waterford']


查看完整回答
反对 回复 2021-06-01
  • 3 回答
  • 0 关注
  • 156 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号