【问题标题】:python: Finding a index in one list and then replacing second list with the item from a index in first listpython:在一个列表中查找索引,然后用第一个列表中的索引中的项目替换第二个列表
【发布时间】:2021-04-14 13:43:54
【问题描述】:

我目前正在尝试在列表中查找一个项目,获取它的位置并在另一个列表中找到相同的位置,以将其替换为第一个列表中的项目。

示例:

list_1 = ['a', 'b', 'c', 'a', 'b', 'c' ]

list_2 = ['1', '2', '3', '1', '2', '3']

我会尝试找到'a',获取它的索引,在第二个列表中找到索引并替换该索引中的那个项目。所以那些在list_2中变成'a'

【问题讨论】:

  • 这是一个非常简单的任务。到目前为止,您尝试过什么?

标签: python arrays list replace


【解决方案1】:

如果我理解正确,所需的输出将是:['a', '2', '3', '1', '2', '3']。所以我会这样编码:

list_1 = ['a', 'b', 'c', 'a', 'b', 'c']

list_2 = ['1', '2', '3', '1', '2', '3']


def replace_symbol(list_1, list_2, symbol):
    symbol_to_replace = list_1.index(symbol)
    list_2[symbol_to_replace] = symbol
    print(list_2)  # prints ['a', '2', '3', '1', '2', '3']
    return list_2


replace_symbol(list_1, list_2, 'a')  # pass the symbol to replace in the function call
        

【讨论】:

    【解决方案2】:

    您可以使用<sequence>.index(<value>) 找到任何值的索引。

    此“索引代码”在第一个列表中找到所需的项目,并在 list_2 中使用刚刚找到的索引插入相同的项目:

    list_1 = ['b', 'c', 'a', 'b', 'c' ]
    list_2 = ['1', '2', '3', '1', '2', '3']
    
    item = 'a'
    item_index = list_1.index(item)
    list_2.insert(item_index, item)
    
    print(list_1)
    print(list_2)
    

    在上面的例子中,输出是这样的:

    ['b', 'c', 'a', 'b', 'c']
    ['1', '2', 'a', '3', '1', '2', '3']
    

    【讨论】:

      【解决方案3】:

      如果该字母只有一个实例,您可以使用 list_1.index('a') 来获取 'a' 索引。但是我可能会看到您的列表中有重复的值,所以 for 循环应该可以解决这个问题。

      list_1 = ['a', 'b', 'c', 'a', 'b', 'c' ]
      list_2 = ['1', '2', '3', '1', '2', '3']
      indexes = []
      search_value = 'a'
      for e, value in enumerate(list_1):  # e is basically our counter here so we use it later to find current position index
      if value == search_value:
          indexes.append(e)
          
      if len(indexes) > 0:  # check if our indexes list is not empty
          for index in indexes:
             list_2[index] = search_value
          
      print(list_2)
      

      这将导致:

      ['a', '2', '3', 'a', '2', '3']
      

      【讨论】:

        【解决方案4】:

        这样的?

        def replace_el(l1, l2, el):
            try:
                l2[l1.index(el)] = el
            except ValueError:
                pass
        
        list_1 = ['a', 'b', 'c', 'a', 'b', 'c' ]
        list_2 = ['1', '2', '3', '1', '2', '3']
        
        replace_el(list_1, list_2, 'k')
        print(list_2)
        replace_el(list_1, list_2, 'a')
        print(list_2)
        

        这是输出:

        ['1', '2', '3', '1', '2', '3']
        ['a', '2', '3', '1', '2', '3']
        

        函数replace_ell2的元素替换在l1el的相同位置。如果el 不在l1 中,则l2 不变。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-01-11
          • 2012-01-10
          • 1970-01-01
          • 1970-01-01
          • 2019-10-10
          • 2016-11-08
          相关资源
          最近更新 更多