【问题标题】:Why does Python 'for word in words:' iterate on individual characters instead of words?为什么 Python 'for word in words:' 迭代单个字符而不是单词?
【发布时间】:2014-06-08 06:22:23
【问题描述】:

当我在字符串words 上运行以下代码时:

def word_feats(words):
    return dict([(word, True) for word in words])
print(word_feats("I love this sandwich."))

我得到的是字母而不是单词的输出字典理解:

{'a': True, ' ': True, 'c': True, 'e': True, 'd': True, 'I': True, 'h': True, 'l': True, 'o': True, 'n': True, 'i': True, 's': True, 't': True, 'w': True, 'v': True, '.': True}

我做错了什么?

【问题讨论】:

    标签: python string for-loop iteration string-iteration


    【解决方案1】:

    您需要明确拆分空格上的字符串:

    def word_feats(words):
        return dict([(word, True) for word in words.split()])
    

    这使用不带参数的str.split(),在任意宽度的空白处分割(包括制表符和行分隔符)。 否则,字符串是单个字符的序列,直接迭代实际上只会遍历每个字符。

    然而,拆分成单词必须是您需要自己执行的显式操作,因为不同的用例对如何将字符串拆分为单独的部分有不同的需求。例如,标点符号算不算?括号或引用呢,也许按这些分组的单词不应该分开?等等。

    如果您所做的只是将所有值设置为True,那么改用dict.fromkeys() 会更有效率:

    def word_feats(words):
        return dict.fromkeys(words.split(), True)
    

    演示:

    >>> def word_feats(words):
    ...     return dict.fromkeys(words.split(), True)
    ... 
    >>> print(word_feats("I love this sandwich."))
    {'I': True, 'this': True, 'love': True, 'sandwich.': True}
    

    【讨论】:

      【解决方案2】:

      你必须split words 字符串:

      def word_feats(words):
          return dict([(word, True) for word in words.split()])
      print(word_feats("I love this sandwich."))
      

      示例

      >>> words = 'I love this sandwich.'
      >>> words = words.split()
      >>> words
      ['I', 'love', 'this', 'sandwich.']
      

      您还可以使用其他字符进行拆分:

      >>> s = '23/04/2014'
      >>> s = s.split('/')
      >>> s
      ['23', '04', '2014']
      

      您的代码

      def word_feats(words):
          return dict([(word, True) for word in words.split()])
      print(word_feats("I love this sandwich."))
      
      [OUTPUT]
      {'I': True, 'love': True, 'this': True, 'sandwich.': True}
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-06-20
        • 2021-05-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多