Message Boards Message Boards

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

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!

POSTED BY: Juerg Baertsch
2 Replies
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 BY: Robert Hanlon
Posted 10 years ago

Thanks a lot for this two perfect solutions, Robert! I'm happy now ;)

POSTED BY: Juerg Baertsch
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract