Python - converting a comma separated string to shorthand string list

Given a Python line like this:

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

I would like to convert it to 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, if you set a comma string ( location_in ), I would like to copy it to a list ( location_out ) and gradually split it by deleting the first word / phrase each time.

I am new to Python. Any ideas on a good way to write this? Thanks.

+7
source share
4 answers
 location_in = 'London, Greater London, England, United Kingdom' locations = location_in.split(', ') location_out = [', '.join(locations[n:]) for n in range(len(locations))] 
+24
source

There are many ways to do this, but here is one thing:

 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)) 

More vicious 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) 
+1
source

Here's the worker:

 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 
+1
source
 >>> location_in = 'London, Greater London, England, United Kingdom' >>> location_out = [] >>> loc_l = location_in.split(", ") >>> while loc_l: ... location_out.append(", ".join(loc_l)) ... del loc_l[0] ... >>> location_out ['London, Greater London, England, United Kingdom', 'Greater London, England, United Kingdom', 'England, United Kingdom', 'United Kingdom'] >>> 
0
source

All Articles