如何使用向后组合迭代地拆分字符串?

时间:2018-12-04 20:23:01

标签: python list split combinations

我有一个看起来像这样的字符串列表:

['C04.123.123.123', 'C03.456.456.456', 'C05.789.789.789']

我正尝试拆分每个字符串,以便在句点定界符上获得不同的向后拆分组合。基本上,如果仅以第一个字符串为例,我想得到:

['C04.123.123.123', 'C04.123.123', 'C04.123', 'C04']

我该如何实现?我尝试研究itertools.combinations和标准的拆分功能,但是没有运气。

5 个答案:

答案 0 :(得分:3)

您可以使用列表理解:

d = ['C04.123.123.123', 'C03.456.456.456', 'C05.789.789.789']
new_d = [a+('.' if i else '')+'.'.join(i) for a, *c in map(".".split, d) 
     for i in [c[:h] for h in range(len(c)+1)][::-1]]

输出:

['C04.123.123.123', 'C04.123.123', 'C04.123', 'C04', 'C03.456.456.456', 'C03.456.456', 'C03.456', 'C03', 'C05.789.789.789', 'C05.789.789', 'C05.789', 'C05']

答案 1 :(得分:3)

易于理解的单行代码(使用起来不太容易:)),使用str.rsplit并通过maxsplit逐渐增加点数:

lst = ['C04.123.123.123', 'C03.456.456.456', 'C05.789.789.789']

result = [x.rsplit(".",i)[0] for x in lst for i in range(x.count(".")+1) ]

结果:

['C04.123.123.123',
 'C04.123.123',
 'C04.123',
 'C04',
 'C03.456.456.456',
 'C03.456.456',
 'C03.456',
 'C03',
 'C05.789.789.789',
 'C05.789.789',
 'C05.789',
 'C05']

唯一让我烦恼的是,它只是为了保留第一个元素而经常调用split。不幸的是,没有内置的惰性split函数可以调用next

答案 2 :(得分:0)

NSFileWrapper *bundleFileWrapper = [[NSFileWrapper alloc] initDirectoryWithFileWrappers:nil];

NSDictionary *fileWrappers = [bundleFileWrapper fileWrappers];

if ([fileWrappers objectForKey:mboxFileName] == nil) {
    NSFileWrapper *textFileWrapper = [[NSFileWrapper alloc] initRegularFileWithContents:mboxData];
    [textFileWrapper setPreferredFilename:mboxFileName];
    [bundleFileWrapper addFileWrapper:textFileWrapper];
}
NSError *error;

BOOL success = [bundleFileWrapper writeToURL:[NSURL fileURLWithPath:path] options:NSFileWrapperWritingAtomic originalContentsURL:NULL error:&error];

NSLog(@"Error = %@",[error localizedDescription]);

或者,您可以start_list = ['C04.123.123.123', 'C03.456.456.456', 'C05.789.789.789'] final_list = [] for item in start_list: broke_up = item.split('.') temp = [] full_item = [] for sect in broke_up: temp.append(sect) full_item.append(".".join(temp)) final_list.extend(full_item) print(final_list) 为原始列表中的每个字符串保留单独的列表。

答案 3 :(得分:0)

尝试一下:

list(accumulate(s.split('.'), lambda a, b: a + '.' + b))[::-1]

答案 4 :(得分:0)

您可以使用itertools.accumulate

from itertools import accumulate
s = 'C04.123.123.123'
# define the incremental step
append = lambda s, e: s + '.' + e
result = list(accumulate(s.split('.'), append))[::-1]