I essentially have two questions, both are related.
1) How do I change a value within a list of lists (I provided a example problem)?
2) Why does my code not work?
I have a list which was created from the Tally function on a text file. The result is shown below...
tally = {{"tree", 5}, {"State", 6}, {"swimming", 3}, {"began",
2}, {"season", 8}, {"Force", 2}, {"Sooners", 10}, {"three",
4}, {"second", 14}, {"medley", 6}, {"relay", 17}, {"junior",
5}, {"sophomore", 3}, {"freshman", 5}, {"coach", 2}, {"Pratt",
2}, {"think", 2}, {"close", 2}, {"thought", 2}, {"events",
8}, {"finished", 9}, {"individual", 4}, {"collected",
4}, {"honors", 4}, {"along", 2}, {"third", 13}, {"showing",
4}, {"swept", 2}, {"first", 5}, {"Junior", 2}, {"star",
22}, {"freestyle", 4}, {"runner", 2}, {"Sooner", 2}, {"scored",
2}, {"respectively", 2}, {"finishes", 4}, {"Sophomore",
2}, {"opening", 3}, {"finish", 2}, {"lifetime", 2}, {"times",
2}, {"posted", 3}, {"marks", 2}, {"Championships",
3}, {"conference", 2}, {"recorded", 2}, {"vital", 2}, {"relays",
4}, {"school", 3}, {"records", 2}, {"earned", 3}, {"fourth",
3}, {"campaign", 2}, {"against", 5}, {"Northern", 6}, {"Colorado",
5}, {"helped", 2}, {"Arizona", 2}, {"Idaho", 2}, {"named",
2}, {"Academic", 2}, {"backstroke", 2}, {"fifth", 3}, {"regular",
2}, {"winning", 2}, {"victorious", 2}, {"sixth", 2}, {"RioRancho",
4}, {"School", 2}};
I want to be able to find the string "star" within the list and change the associated number with that string to 1000. I tried using the following code:
tally /. _?Last@(First@# == "star" &) -> 1000
It does not work the way I want. The number value associated with "star" remains unchanged. I know there is a way to do this. I just can't see it...
Thank you for any assistance!
tally /. {"star", _} -> {"star", 1000}
? $\endgroup$First
part of your pattern works alright, but you can't take theLast
of that. It doesn't mean that the last part of your matching is replaced by 1000. $\endgroup$?
must be followed by a function.First@# == "star" &
is a function but(Last@(First@# == "star" &))
is not 2. you are replacing the whole thing that_ ? ...
matches not just the second part of that subexpression. $\endgroup$