2011-05-13 107 views
7

给出一个Python字符串是这样的: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

呃..不是'locato n_out只是'[location_in]'?你需要进一步澄清。 – Pwnna 2011-05-13 23:06:36

+4

不。我不知道你在做什么,但这可能是错误的做法。 – 2011-05-13 23:15:06

+0

下面的一些很好的答案。谢谢大家的帮助! – Federico 2011-05-14 08:29:07

回答

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

的方式来做到这一点充足,但这里有一个:

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

+1不分割'location_in'。 – 9000 2011-05-13 23:25:23

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 
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'] 
>>> 
相关问题