如何将索引列表(称为" indlst"),如[[1,0],[3,1,2]]对应元素[1] [0]和[ 3] [1] [2]给定列表(称为" lst"),用于改变原始列表中的各自元素?另请注意,索引是指嵌套到任意深度的元素。例如,给定
// Your secret key can be anything you want
$secretKey = 'oldlaravel.dev';
Route::group(['domain' => 'oldlaravel.dev'], function() use ($secretKey) {
Route::get('/', function() use ($secretKey) {
$hashedToken = Hash::make($secretKey);
return Redirect::to("http://newlaravel.dev?token=$hashedToken", 301);
});
});
Route::group(['domain' => 'newlaravel.dev'], function() use ($secretKey) {
Route::get('/', function() use ($secretKey) {
if (Request::get('token')) {
if (Hash::check($secretKey, Request::get('token'))) {
echo 'You got here by redirect from my old domain!';
} else {
echo 'Who the hell are you?!'; //came here with an invalid token parameter
}
} else {
echo 'You got here directly!';
}
});
});
输出应对应于[" b"," h"]。我知道我可以通过以下代码段获得这一点(参见Use list of nested indices to access list element):
indlst = [[1,0], [3,1,2]]
lst = ["a", ["b","c"], "d", ["e", ["f", "g", "h"]]]
required_output = [lst[1][0],lst[3][1][2]]
但是,我需要在原始列表中更改这些元素。例如,将每个访问过的元素更改为" CHANGED":
for i in indlst:
temp = lst
for j in i:
temp = temp[j]
print(temp)
b
h
答案 0 :(得分:0)
我的解决方案是从最深层的元素开始,按照以下方式返回:
def set_from_indices(value, indices, array):
for i in reversed(range(len(indices))): # Pulls back the deepest element available each loop
current = array.copy() # Without .copy() any changes to current would also change array.
for index, indice in enumerate(indices):
if index == i: # If we are on the deepest element available this loop
current[indice] = value.copy() if isinstance(value, list) else value # Without the .copy() current[indice] just becomes '...'
value = current.copy() # Make the
break
current = current[indice]
return value
indlst = [[0,1], [0,0,1], [0,0,0,1]]
lst = [[[[4,3],2],1],0]
for indices in indlst:
lst = set_from_indices("CHANGED", indices, lst)