Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - convert comma separated string into reducing string list

Tags:

python

Given a Python string like this:

location_in = 'London, Greater London, England, United Kingdom'

I would like to convert it into a list like this:

location_out = ['London, Greater London, England, United Kingdom',
                'Greater London, England, United Kingdom',
                'England, United Kingdom',
                'United Kingdom']

In other words, given a comma separated string (location_in), I would like to copy it to a list (location_out) and gradually break it down by removing the first word/phrase each time.

I'm a Python newbie. Any ideas on a good way to write this? Thanks.

like image 224
Federico Avatar asked May 13 '11 23:05

Federico


3 Answers

location_in  = 'London, Greater London, England, United Kingdom'
locations    = location_in.split(', ')
location_out = [', '.join(locations[n:]) for n in range(len(locations))]
like image 139
Peter Collingridge Avatar answered Sep 28 '22 11:09

Peter Collingridge


Here's a working one:

location_in = 'London, Greater London, England, United Kingdom'
loci = location_is.spilt(', ') # ['London', 'Greater London',..]
location_out = []
while loci:
  location_out.append(", ".join(loci))
  loci = loci[1:] # cut off the first element
# done
print location_out
like image 20
9000 Avatar answered Sep 28 '22 12:09

9000


Plenty of ways to do this, but here's one:

def splot(data):
  while True:
    yield data
    pre,sep,data=data.partition(', ')
    if not sep:  # no more parts
      return

location_in = 'London, Greater London, England, United Kingdom'
location_out = list(splot(location_in))

A more perverse solution:

def stringsplot(data):
  start=-2               # because the separator is 2 characters
  while start!=-1:       # while find did find
    start+=2             # skip the separator
    yield data[start:]
    start=data.find(', ',start)
like image 40
Yann Vernier Avatar answered Sep 28 '22 13:09

Yann Vernier