zoukankan      html  css  js  c++  java
  • 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']]

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

    >>> 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']]

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

    人生苦短,何不用python
  • 相关阅读:
    我们在囧途之程序员转型记
    项目开发应遵循1+7还是7+1?
    自己用的一款模板解析程序(支持插件和扩展)(思路讨论和使用体验)
    设计的核心任务之一:层次的控制
    【设计 = 编码】 VS 【设计 ≠ 编码】
    从一生的角度看程序员的学习和发展
    编码质量与命名
    软件开发十年小史
    设计的核心任务之三:确保正交性
    国内外软件开发上的差距与分析
  • 原文地址:https://www.cnblogs.com/yqpy/p/8372772.html
Copyright © 2011-2022 走看看