0
|
5164 Views
|
2 Replies
|
3 Total Likes
View groups...
Share
GROUPS:

# Replace the last Element that matches a pattern from a List

Posted 10 years ago
 Hello I have a list perhaps like this: list = {1, {1, 2, 3}, {{1, 2}, 3}}  I search all postions with the Value 1: pos = Position[list, 1] {{1},{2,1},{3,1,1}}  I want to replace the 1 at the last position: list[[3, 1, 1]] = 9; {1,{1,2,3},{{9,2},3}}  My problem is, that i want to take the position for the last 1 from the position-list (I saved above as pos). list[[pos[[-1]]]] = 9;  I know that this doesnt work, because pos[[-1]] is a list. Is there a solution, do make it working? Would be great if someone could help me. Kind regards!
2 Replies
Sort By:
Posted 10 years ago
 list = {1, {1, 2, 3}, {{1, 2}, 3}}; pos = Position[list, 1]; list[[Sequence @@ pos[[-1]]]] = 9; list  {1, {1, 2, 3}, {{9, 2}, 3}} Alternatively, list = {1, {1, 2, 3}, {{1, 2}, 3}}; pos = Position[list, 1]; ReplacePart[list, pos[[-1]] -> 9]  {1, {1, 2, 3}, {{9, 2}, 3}}
Posted 10 years ago
 Thanks a lot for this two perfect solutions, Robert! I'm happy now ;)