Python - 将逗号分隔的字符串转换为简化的字符串列表

8

假设有一个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新手。有什么好的编写方法吗?谢谢。

嗯... locaton_out 不就是 [location_in] 吗?你需要进一步澄清。 - Pwnna
4
不要。我不知道你在做什么,但这可能是错误的方法。 - Winston Ewert
1
@WinstonEwert 如果你不知道他在做什么,你怎么知道这是错误的方法? - Ben Mordecai
@BenMordecai,请求的输出很奇怪,让我觉得他尝试做的事情可能有更好的方法。 - Winston Ewert
@BenMordecai,你的例子看起来很合理。奇怪的是想要一个逗号分隔的字符串列表。我看不出那可能有什么帮助。 - Winston Ewert
显示剩余3条评论
4个回答

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

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']
>>> 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接