【问题标题】:Is there a method like .replace() for list in python? [duplicate]python中的列表是否有类似.replace()的方法? [复制]
【发布时间】:2017-08-23 18:03:08
【问题描述】:

我已经使用 .split() 方法从字符串中创建了一个列表。 例如: string = "I like chicken" 我将使用 .split() 来制作字符串 ['I','like','chicken'] 中的单词列表 现在,如果我想用其他东西替换 'chicken',我可以使用什么方法,比如 .replace() 但对于列表?

【问题讨论】:

    标签: python string list methods


    【解决方案1】:

    不存在这样的方法,但列表理解可以很容易地适应目的,list 不需要新方法:

    words = 'I like chicken'.split()
    replaced = ['turkey' if wd == "chicken" else wd for wd in words]
    print(replaced)
    

    哪个输出:['I', 'like', 'turkey']

    【讨论】:

      【解决方案2】:

      没有内置任何东西,但它只是一个循环就地进行替换:

      for i, word in enumerate(words):
          if word == 'chicken':
              words[i] = 'broccoli'
      

      如果总是只有一个实例,则使用更短的选项:

      words[words.index('chicken')] = 'broccoli'
      

      或使用列表推导来创建新列表:

      new_words = ['broccoli' if word == 'chicken' else word for word in words]
      

      其中任何一个都可以封装在一个函数中:

      def replaced(sequence, old, new):
          return (new if x == old else x for x in sequence)
      
      
      new_words = list(replaced(words, 'chicken', 'broccoli'))
      

      【讨论】:

      • 如果我只想更改单词的部分内容而我的列表中的值超过 2 个部分怎么办?
      猜你喜欢
      • 2013-01-03
      • 1970-01-01
      • 1970-01-01
      • 2021-07-30
      • 1970-01-01
      • 2012-07-08
      • 1970-01-01
      • 2013-06-07
      • 2011-10-08
      相关资源
      最近更新 更多