[英]How to replace indexes by values from different list?
我有两个清单:
test_list1 = [2, 3, 4, 5, 2, 4]
test_list2 = [[1, 5], [4, 2, 3], [0]]
我想用test_list2
中的值替换test_list1
中的索引,这样结果将是:
[[3, 4], [2, 4, 5], [2]]
我试过这个:
res = [test_list1[idx] for idx in test_list2]
我注意到我的代码仅适用于没有子列表的列表
您可以使用递归 function。 这将 go 通过任意嵌套列表替换值。
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)
给出:
[[3, 4], [2, 4, 5], [2]]
具有列表理解和 map function 的 oneliner 可能如下所示:
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]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.