我希望进行如下转换:
['test.smth.test', 'test.smth'] -> ['test.smth']
['test.smth.test', 'test.smth.another'] -> ['test.smth.test', 'test.smth.another']
['test.one', 'test.smth'] -> ['test.one', 'test.smth']
['test.one', 'test', 'test.smth.name'] -> ['test']
['test_another.one.name', 'test', 'test.smth.name'] -> ['test', 'test_another.one.name']
我最终得到的代码是:
def format_fields(fields):
fields_data = defaultdict(list)
for field in fields:
split = field.split('.')
base = split[0]
already = False
for i in reversed(range(len(split))):
if split[:i] in fields_data[base]:
already = True
break
if already:
continue
current = [i for i in fields_data[base] if len(i) < len(split)
or i[len(split) - 1] != split[-1]]
fields_data[base] = current + [split]
return ['.'.join(value) for group in fields_data.values() for value in group]
这个方法似乎可行,但是是否有更易读/更聪明的解决方案,或者有第三方库可以实现这个功能?