【问题标题】:python replacing item in listpython替换列表中的项目
【发布时间】:2012-11-11 08:22:25
【问题描述】:

您好,我的问题与很久以前这里某个用户的帖子有关:

Find and replace string values in Python list

针对我的具体情况。我有一个这样的列表:

appl =  ['1', 'a', 'a', '2', 'a']

我只想用一个空格替换“a”的“单个未知”实例(它保留了“a”曾经所在的位置)。我不确定如何只为一个角色做这件事。任何人都可以帮忙吗?提前致谢。

编辑:我应该提到我需要使用“索引”函数来首先定位“a”,因为它是一个不断变化的变量。然后我需要替换字符的代码。

EDIT2:很多人都假设索引为 2,但我想指出,字符的索引是未知的。此外,“a”将出现在列表中大约 20 次(将保持固定数量),但它们的位置会发生变化。我想根据用户输入替换“a”。这是我正在使用的实际列表:

track  [2] =   ["|","@","|"," ","|"," ","|"," ","|"," ","|"," ","|"," ","|"," ","|"," ","|"," ","|"," ","|"," ","|"," ","|"," ","|"," ","|"," ","|"," ","|"," ","|"," ","|"," ","|"]

@ 是一个字符,|是一个边框,“”是一个空格。 用户输入输入以选择@向右移动多少,并显示一个新图像,该图像显示@的新位置,@的旧位置被替换为空格。列表的长度保持不变。这是我的问题的上下文。

【问题讨论】:

    标签: python list replace


    【解决方案1】:

    您可以通过遍历列表并存储元素为'a' 的索引来简单地找到第二次出现的索引,直到找到两个:

    >>> appl = ['1', 'a', 'a', '2', 'a']
    >>> idxs = (i for i,c in enumerate(appl) if c == 'a')
    >>> next(idxs)
    0
    >>> appl[next(idxs)] = ''
    >>> appl
    ['1', 'a', '', '2', 'a']
    

    【讨论】:

      【解决方案2】:

      您可以使用 index 以及循环来实现此目标。 这是它的一个小功能:

      def replace_element(li, ch, num, repl):
          last_found = 0
          for _ in range(num):
              last_found = li.index(ch, last_found+1)
          li[li.index(ch, last_found)] = repl
      

      使用:

      replace_element(appl, 'a', 2, ' ')
      

      这个方法特别好,因为它在字符不在列表中时会抛出以下错误:

      ValueError: 'a' is not in list
      

      【讨论】:

      • 这不对appl.index('a', 2)表示从位置2开始,没有找到第二个匹配项。
      • appl.index('a', 2) means find the second index of a。不,它没有。这意味着搜索从字符 2 开始。
      • @phihag 啊抱歉,脑子放屁了,谢谢指正。
      【解决方案3】:
      appl = ['1', 'a', 'a', '2', 'a']
      a_indices = [i for i, x in enumerate(appl) if x == 'a']
      
      if len(a_indices) > 1:
          appl[a_indices[1]] = ' '
      

      【讨论】:

      • 这是否也只是第二次出现?
      【解决方案4】:

      首先,找到第一次出现的值:

      >>> appl = ['1', 'a', 'a', '2', 'a']
      >>> first = appl.index('a')
      >>> first
      1
      

      要找到第二个,从第一个位置加一开始:

      >>> second = appl.index('a', first+1)
      >>> second
      2
      

      然后将该位置设置为您想要的空间:

      >>> appl[second] = ' '
      >>> appl
      ['1', 'a', ' ', '2', 'a']
      

      【讨论】:

        【解决方案5】:

        您的列表("|""@")似乎很短,而"@" 总是存在,只是在不同的位置。在这种情况下,您可以在一行中替换appl 列表中第一次出现的"@"

        appl[appl.index("@")] = " "
        

        如果列表很大并且项目可能不存在:

        i = next((i for i, x in enumerate(lst) if x == item), None)
        if i is not None:
           lst[i] = replacement
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-12-02
          • 1970-01-01
          • 2021-10-23
          • 2016-01-13
          • 2012-08-15
          • 2021-03-06
          相关资源
          最近更新 更多