给出一个像这样的Python字符串:
location_in = 'London, Greater London, England, United Kingdom'
我想将其转换为这样的列表:
location_out = ['London, Greater London, England, United Kingdom',
'Greater London, England, United Kingdom',
'England, United Kingdom',
'United Kingdom']
换句话说,给定逗号分隔的字符串(location_in
),我想将其复制到列表(location_out
)并逐渐删除它,每次删除第一个单词/短语
我是一个Python新手。写这个的好方法有什么想法吗?感谢。
答案 0 :(得分:24)
location_in = 'London, Greater London, England, United Kingdom'
locations = location_in.split(', ')
location_out = [', '.join(locations[n:]) for n in range(len(locations))]
答案 1 :(得分:1)
有很多方法可以做到这一点,但这里有一个:
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))
更有悖常理的解决方案:
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)
答案 2 :(得分:1)
这是一个有效的工作:
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
答案 3 :(得分:0)
>>> 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']
>>>