gpt4 book ai didi

python - 根据常见项目减少python中的列表

转载 作者:行者123 更新时间:2023-11-28 18:15:34 24 4
gpt4 key购买 nike

我想做这样的改造:

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

它似乎可行,但是否有更易读/更聪明的解决方案,或者可以做到这一点的第三方库?

最佳答案

这应该可行,基本上您需要找到任何其他字段中未包含的每个字段,在每个字段的末尾添加一个点,以免出现子字符串错误,例如“test_another”和“test”:

cases = [
['test.smth.test', 'test.smth'],
['test.smth.test', 'test.smth.another'],
['test.one', 'test.smth'],
['test.one', 'test', 'test.smth.name'],
['test_another.one.name', 'test', 'test.smth.name']
]

def filterFields(fields):
cFields = [field + '.' for field in fields]
return [field[:-1] for index, field in enumerate(cFields) if all(field.find(f) != 0 for f in cFields[:index] + cFields[index+1:])]

for case in cases:
print(case, '->', filterFields(case))

WORKING CODE

关于python - 根据常见项目减少python中的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48639814/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com