-3

example: I have the state Arkansas and a list of some of its counties as follows:

ar
randolph
franklin
lawrence
scott
sharp
carroll
greene
van buren
clay
montgomery
cleburne
fulton
polk
boone
madison
marion
baxter
searcy
stone
newton

The state is the two-letter abbreviation at the beginning of the list. For this example, how can I make it such that to each of these counties is appended ", ar" e.g. randolph, ar; franklin, ar; newton, ar etc.

Hircarra
  • 1
  • 2
  • a for loop perhaps? `['ar '+item for item in counties]` ? – Devesh Kumar Singh Jun 26 '19 at 14:45
  • 2
    What have you tried so far ? – Alexandre B. Jun 26 '19 at 14:45
  • Given list `a = ['ar', 'bbbb', 'cccc', 'dddd']` doing `['%s, %s' % (a[0], s) for s in a[1:]]` will give `['ar, bbbb', 'ar, cccc', 'ar, dddd']`. – Steven Rumbalski Jun 26 '19 at 14:47
  • I can't make the question clearer. What is appended is specified IN THE LIST. "ar" is an EXAMPLE. The only difference between that line and the rest is that it's two letters long. – Hircarra Jun 26 '19 at 14:50
  • Have a look [here](https://stackoverflow.com/questions/2050637/appending-the-same-string-to-a-list-of-strings-in-python) and [this](https://stackoverflow.com/questions/18425696/adding-prefix-to-string-in-a-file) – Sheldore Jun 26 '19 at 14:52
  • `['{}, {}'.format(ct, st) for it in [itertools.groupby(a, lambda item: len(item) == 2)] for _, sts in it for st in sts for _, cts in it for ct in cts]` where `a` is your list. – Steven Rumbalski Jun 26 '19 at 15:16
  • Or `st = '';[f'{ct}, {st}' for ct in a if len(ct) != 2 or not (st := ct)]` if you want to abuse assignment expressions ([PEP 572](https://www.python.org/dev/peps/pep-0572/)) in the upcoming Python 3.8. – Steven Rumbalski Jun 26 '19 at 15:39

1 Answers1

1
list_of_counties = ['ar', 'franklin', .....]
list_to_append = []

for county in list_of_counties:
   if len(county) == 2:
       abbreviation = ' ,' + county
   else:
       list_to_append.append(county + abbreviation)

This is given an abbreviation comes first in the list.

Gabriel Petersson
  • 8,434
  • 4
  • 32
  • 41
  • The entire problem is that in this EXAMPLE, ", ar" is PULLED FROM THE LIST ITSELF. I don't know how to make this clearer. The difference between the state and the counties is that it's always a two-letter abbreviation, so I suppose that's how they can be discerned. – Hircarra Jun 26 '19 at 14:58
  • Oh so you mean that every time a 2 letter string comes up in the list, you need to use this as your abbreviation? – Gabriel Petersson Jun 26 '19 at 14:59
  • Every time a 2-letter string comes up, everything after it, until the next 2-letter string, needs to be appended ", " plus the 2-letter string. – Hircarra Jun 26 '19 at 15:01
  • @Hircarra Was this what you meant? – Gabriel Petersson Jun 26 '19 at 15:27