给定这样的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新手。有什么好主意可以写吗?谢谢。
最佳答案
location_in = 'London, Greater London, England, United Kingdom'
locations = location_in.split(', ')
location_out = [', '.join(locations[n:]) for n in range(len(locations))]
关于Python-将逗号分隔的字符串转换为精简字符串列表,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5998569/