python多行代码简化

python中,可以把多行代码简化为一行,把for循环和if条件判断都集中到一行里来写,示例如下:

>>> from nltk.corpus import stopwords
>>> english_stopwords = stopwords.words('english')#加载nltk中的英文停用词数据#创建一个列表,内含3个单词列表
>>> texts_tokenized = [['writing', 'ii', 'rhetorical', 'composing', 'rhetorical', 'composing'],['engages', 'series', 'interactive', 'reading'],['research', 'composing', 'activities', 'along', 'assignments', 'designed', 'help']]#用多行代码对texts_tokenized去停用词
>>> text_filtered_stopwords = [[word for word in document if not word in english_stopwords] for document in texts_tokenized]
>>> text_filtered_stopwords
[['writing', 'ii', 'rhetorical', 'composing', 'rhetorical', 'composing'], ['engages', 'series', 'interactive', 'reading'], ['research', 'composing', 'activities', 'along', 'assignments', 'designed', 'help']]

然后改成用多行的常规写法:

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:778463939
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
>>> texts_tokenized = [['writing', 'ii', 'rhetorical', 'composing', 'rhetorical', 'composing'],['engages', 'series', 'interactive', 'reading'],['research', 'composing', 'activities', 'along', 'assignments', 'designed', 'help']]
>>> documents = []
>>> texts_filtered_stopwords =[]
>>> for document in texts_tokenized:
      for word in document:
          if word not in english_stopwords:
              documents.append(word)
      texts_filtered_stopwords.append(document)

    
>>> texts_filtered_stopwords
[['writing', 'ii', 'rhetorical', 'composing', 'rhetorical', 'composing'], ['engages', 'series', 'interactive', 'reading'], ['research', 'composing', 'activities', 'along', 'assignments', 'designed', 'help']]

可以看到得出一样的结果,但是代码的效率和简洁程度大大提升

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值