[英]python: Finding a index in one list and then replacing second list with the item from a index in first list
我目前正在尝试在列表中查找一个项目,将其设为 position 并在另一个列表中找到相同的 position 以将其替换为第一个列表中的项目。
例子:
list_1 = ['a', 'b', 'c', 'a', 'b', 'c' ]
list_2 = ['1', '2', '3', '1', '2', '3']
我会尝试找到'a'
,获取它的索引,在第二个列表中找到索引并替换该索引中的那个项目。 所以那些在list_2
中变成'a'
如果我正确理解所需的 output 将是: ['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
您可以使用<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)
在上面的例子中,output 是这样的:
['b', 'c', 'a', 'b', 'c']
['1', '2', 'a', '3', '1', '2', '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']
像这样的东西?
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)
这是 output:
['1', '2', '3', '1', '2', '3']
['a', '2', '3', '1', '2', '3']
function replace_el
替换了l2
中l1
中el
的相同 position 中的元素。 如果el
不在l1
中,则l2
不变。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.