Reputation: 521
I have 2 Python lists: list_a and list_b
I would like to adjust list_b in the following way:
Note: list_a and list_b are not necessarily in order, but that the ordered set of list_a's elements will always start at 0 and end at the number of unique elements in list_a, minus 1. However, list_b's elements can be in any order and skip numbers, although the minimum value for list_b is 0. Any number in either list can be repeated several times.
This may be a little confusing, so a couple examples:
Example 1:
list_a = [2,1,0,1,2,2]
list_b = [3,0,6,1,6,3,3]
In the example above, I would want list_b to be replaced with
list_b_new = [3,0,4,1,4,3,3]
Explanation: All of the elements except for elements 0,2,4,5,6 could be found in list_a, so the only potential change is there. Since the 3's are already one number up from the max in list_a, we don't need to change those. However, we want to change the 6's to 4's because that is the next number up from the maximum number in list_a that isn't already used by list_b.
Example 2:
list_a = [4,0,0,1,2,2,3]
list_b = [8]
list_b_new = [5]
Explanation: List b only has one number, and that number is not found in list_a, so we replace it with the next number up from the maximum in list_a, which is 5.
Example 3:
list_a = [5,0,3,1,2,2,4]
list_b = [0,5,9,8,8,9]
list_b_new = [0,5,7,6,6,7]
Explanation: Here, we find that there are two "groups" of elements that are not in list_a: all elements with an 8 and all elements with a 9. All elements in list_b with an 8 should be replaced with a 6 since that is the next number up from the max in list_a. All elements in list_b with a 9 should be replaced with a 7 since that is the next number up from list_a that hasn't been used (we already used up 6 when we replaced the 8's with 6's).
Upvotes: 0
Views: 115
Reputation: 2442
Try this-
list_a = [5,0,3,1,2,2,4]
list_b = [0,5,9,8,8,9]
def update_list(l1, l2):
max_a = max(l1) + 1
l3 = []
map_dict = dict()
for i in set(l2):
if i in l1:
map_dict[i] = i
else:
map_dict[i] = max_a
max_a += 1
for i in l2:
l3.append(map_dict[i])
return l3
print(update_list(list_a, list_b))
Output-
[0, 5, 6, 7, 7, 6]
Upvotes: 1