Message Boards Message Boards

1
|
5395 Views
|
4 Replies
|
2 Total Likes
View groups...
Share
Share this post:

Using ReplaceAll to Extract Parts of a List

Posted 9 years ago

Hello everyone,

I have a list of lists such as

theLists = {
  {"Joe", "123 Oak Street", "Pine City", "MA", 10456, 
   "More info on Joe", "Still more info on Joe"},
  {"Mary", "654 Hill Avenue", "Grove City", "FL", 60834, 
   "More info on Mary", "Still more info on Mary", 
   "And even more info on Mary"}
  }

In this case, there is a name, street address, city, state, zip code, and then any number of items of additional information. What I want to do is strip away the addresses (everything up to and including the zip codes) and keep the trailing information. The number of items making up an address also vary.

The following works by checking for a state followed by an integer that represents a zip code. But as you can see, I had to manually specify a (partial) list of states to check.

theLists /. {___, "CA" | "MA" | "FL" | "MD", _Integer, x__} -> {x}

Is there some way to use MemberQ to check a predefined list of all states?

Gregory

POSTED BY: Gregory Lypny
4 Replies
Posted 9 years ago

Hi Okkes,

Thank you kindly for the suggestion. In may case, the position of the state abbreviation and zip code, although adjacent to one another, varies from list to list.

Gregory

POSTED BY: Gregory Lypny
Posted 9 years ago

If all your list is in that order this also works

  Table[Drop[theLists[[i]], {2, 5}], {i, 1, Length@theLists}]      


 {{"Joe", "More info on Joe", 
          "Still more info on Joe"}, {"Mary", "More info on Mary", 
          "Still more info on Mary", "And even more info on Mary"}}
POSTED BY: Okkes Dulgerci
Posted 9 years ago

Hi Vitaliy,

Thank you very much for this tip! It is the condition operator (/;) that I failed to consider because I have never used it much. I can see now that it will be useful in many situations.

Nice of you to keep their names too.

Regards,

Gregory

POSTED BY: Gregory Lypny

Perhaps (I also keep name):

states = EntityValue[
EntityClass["AdministrativeDivision", "AllUSStatesPlusDC"], 
EntityProperty["AdministrativeDivision", "StateAbbreviation"]]

{"AZ", "CA", "GA", "IN", "MT", "OH", "VA", "KS", "MA", "NE", "OK", "AK", "SD", "HI", "AL", "AR", "CO", "CT", "DE", "DC", "FL", "ID", "IL", "IA", "KY", "LA", "ME", "MD", "MI", "MN", "MS", "MO", "NV", "NH", "NJ", "NM", "NY", "NC", "ND", "OR", "PA", "RI", "SC", "TN", "TX", "UT", "VT", "WA", "WV", "WI", "WY"}

theLists /. {y_, ___, s_ /; MemberQ[states, s], _Integer, x__} -> {y, x}

{{"Joe", "More info on Joe", "Still more info on Joe"}, {"Mary", "More info on Mary", "Still more info on Mary", "And even more info on Mary"}}

POSTED BY: Vitaliy Kaurov
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