I have two lists:
test_list1 = [2, 3, 4, 5, 2, 4]
test_list2 = [[1, 5], [4, 2, 3], [0]]
I want to replace the indexes in test_list2
by the values in test_list1
such that the result would be:
[[3, 4], [2, 4, 5], [2]]
I have tried this:
res = [test_list1[idx] for idx in test_list2]
I have notice that my code only works for a list without sublists
You can use a recursive function. This will go through an arbitarily nested list, replacing the values.
def replace(lst, replacements):
for i, val in enumerate(lst):
if isinstance(val, list):
replace(val, replacements)
else:
lst[i] = replacements[val]
test_list1 = [2, 3, 4, 5, 2, 4]
test_list2 = [[1, 5], [4, 2, 3], [0]]
replace(test_list2, test_list1)
print(test_list2)
Gives:
[[3, 4], [2, 4, 5], [2]]
A oneliner with list comprehension and map function could look like this:
test_list1 = [2, 3, 4, 5, 2, 4]
test_list2 = [[1, 5], [4, 2, 3], [0]]
output = list(map(lambda x: [test_list1[y] for y in x], test_list2))
print(output)
# [[3, 4], [2, 4, 5], [2]]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.