【问题标题】:Append letter to end of each string in list in python [duplicate]将字母附加到python列表中每个字符串的末尾[重复]
【发布时间】:2020-08-15 03:04:00
【问题描述】:

我需要通过在列表中每个单词的末尾添加 d 或 ed 来使这些单词成为过去时,具体取决于单词是否以“e”结尾。我试图把它们放在第二个过去时词列表中。

我正在尝试使用我已经掌握的基本知识。这会在 .append 行引发错误,说列表索引必须是整数而不是字符串。我有点卡住了,有什么想法吗?

words = ["adopt", "bake", "beam", "confide", "grill", "plant", "time", "wave", "wish"]
past_tense = []

for i in words:    
    if i[-1] == 'e':
        past_tense.append(words[i] + 'd')
    else:
        past_tense.append(words[i] + 'ed')

【问题讨论】:

  • 您将自己与命名混淆了。将循环更改为for word in words 并从那里开始
  • i 是一个词,而不是一个数字。你不能用字符串索引到列表中
  • 这能回答你的问题吗? How to update strings in a list based on condition。根据您的问题调整代码应该相当容易。

标签: python string list append


【解决方案1】:

当您执行for i in words: 时,您实际上将“i”设置为单词列表中的实际项目(在本例中为单词),因此您可以看到“i”是一个字符串而不是整数。

您的错误来自这一行:

past_tense.append(words[i] + 'd')

因为,正如我已经说过的,你不能使用 'i' 作为索引,因为它是一个字符串。

所以你的代码必须是:


words = ["adopt", "bake", "beam", "confide", "grill", "plant", "time", "wave", "wish"]
past_tense = []

for i in words:    
    if i[-1] == 'e':
        past_tense.append(i + 'd')
    else:
        past_tense.append(i + 'ed')

或者如果你使用for i in range(0,len(words)):,这意味着'i'将从0变为单词列表的长度-1:

words = ["adopt", "bake", "beam", "confide", "grill", "plant", "time", "wave", "wish"]
past_tense = []

for i in range(0,len(words)) :    
    if words[i][-1] == 'e':
        past_tense.append(words[i] + 'd')
    else:
        past_tense.append(words[i] + 'ed')

【讨论】:

    【解决方案2】:

    这些答案都回答了您的直接问题,但如果您正在寻找一种更通用的方法来确定动词的过去时形式(例如,'give' 到 'gave'),一个更细微的库将是能够以更高的精度处理它。 NodeBox 不错。

    python3 -m pip install pattern
    

    然后正如here 解释的那样,您可以使用它的en 包来共轭动词。

    from pattern.en import conjugate
    past_tense = []
    
    for word in words:
        past_tense.append(conjugate(word, tense='past'))
    

    【讨论】:

      【解决方案3】:

      这就是你要找的东西,它只需要一些调整(参见 cmets):

      words = ["adopt", "bake", "beam", "confide", "grill", "plant", "time", "wave", "wish"]
      past_tense = []
      
      for word in words:
      # changed i to word, to reflect what the variable will actually contain.
          if word.endswith('e'):
          # endswith is a nice string method that makes the code very readable.
              past_tense.append(word + 'd')
          else:
              past_tense.append(word + 'ed')
      

      结果:

      >>> print(past_tense)
      ['adopted', 'baked', 'beamed', 'confided', 'grilled', 'planted', 'timed', 'waved', 'wished']
      

      【讨论】:

        【解决方案4】:

        让自己对列表推导感到满意:

        past_tense = [word + ("d" if word.endswith("e") else "ed")
                      for word in words]
        print(past_tense)
        

        产量

        ['adopted', 'baked', 'beamed', 'confided', 'grilled', 'planted', 'timed', 'waved', 'wished']
        


        “老款式”:
        for word in words:
            if word.endswith("e"):
                past_tense.append(word + "d")
            else:
                past_tense.append(word + "ed")
        

        甚至:

        for word in words:
            suffix = "d" if word.endswith("e") else "ed"
            past_tense.append(word + suffix)
        

        【讨论】:

        • 具有双循环和多余内部列表的列表理解?这会不必要地损害性能(+ 看起来很奇怪,因为你实际上只有一个循环)。
        • @a_guest:改了。以前玩过一个变量名,但你是对的。
        【解决方案5】:

        当做for i in words 实际上i 将是数组words 的一个元素所以一个单词

        你不需要数组中的索引,只需要值

        for word in words:    
            if word[-1] == 'e':
                past_tense.append(word + 'd')
            else:
                past_tense.append(word + 'ed')
        

        使用列表推导:

        past_tense = [word + ('d' if word[-1]=='e' else 'ed') for word in words]
        

        【讨论】:

          【解决方案6】:

          您将i 视为带有words[i] 的索引。 i 是你做for i in words: 时的词。将i 替换为word 会更清晰。这样你就不会对索引和单词感到困惑了。

          words = ["adopt", "bake", "beam", "confide", "grill", "plant", "time", "wave", "wish"]
          past_tense = []
          
          for word in words:    
              if word[-1] == 'e':
                  past_tense.append(word + 'd')
              else:
                  past_tense.append(word + 'ed')
          
          print(past_tense)
          # ['adopted', 'baked', 'beamed', 'confided', 'grilled', 'planted', 'timed', 'waved', 'wished']
          

          我们也可以只使用列表推导:

          past_tense = [word + 'd' if word[-1] == 'e' else word + 'ed' for word in words]
          
          print(past_tense)
          # ['adopted', 'baked', 'beamed', 'confided', 'grilled', 'planted', 'timed', 'waved', 'wished']
          

          【讨论】:

            【解决方案7】:
            for i in words: 
            

            这会遍历列表单词中的每个单词。所以这不是一个整数,i 现在是一个字符串。所以words[i] 会通过你得到的错误。

            工作代码:

            words = ["adopt", "bake", "beam", "confide", "grill", "plant", "time", "wave", "wish"]
            past_tense = []
            
            for index,word in enumerate(words):    
                if word[-1] == 'e':
                    past_tense.append(words[index] + 'd')
                else:
                    past_tense.append(words[index] + 'ed')
            

            【讨论】:

            • 他对迭代中的索引和元素本身感到困惑。我只是想消除他的困惑,并想展示一种使用索引和元素@Jan 进行迭代的方法。显然,这里的其他答案更好。我只是想让他知道,还有一个叫enumerate的东西。
            • 好的,谢谢!我一直无法理解何时访问索引或索引中的内容,这确实清除了其中的一部分。
            猜你喜欢
            • 2016-07-20
            • 1970-01-01
            • 2022-12-11
            • 2017-09-29
            • 2014-03-06
            • 2018-03-11
            • 2020-08-19
            • 2013-02-02
            • 1970-01-01
            相关资源
            最近更新 更多