Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
663 views
in Technique[技术] by (71.8m points)

arrays - python: Finding a index in one list and then replacing second list with the item from a index in first list

I am currently trying to find a item in a list, take it's position and find that same position in another list to replace it with the item in the first list.

example:

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

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

I would try to find 'a', take it's index, find the index in the second list and replace that item in that index. So the ones become 'a' in list_2


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You could use list_1.index('a') to get 'a' index if there was only one instance of that letter. But as I might see you have duplicate values in your list so for loop should work for that.

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)

Which will result in :

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...