递归迭代字符串列表以检索字符串组

问题描述 投票:0回答:2

给出以下列表:

inp = ["arg1:", "list", "of", "args", "arg2:", "other", "list"]

如何开发这样的词典?

out = {"arg1": ["list", "of", "args"], "arg2": ["other", "list"]}

这基本上是这样的情况:

  • 循环输入列表,直到找到以冒号为后缀的元素(例如
    arg1:
  • 使用它(不带冒号)在字典中创建一个值为空列表的键
  • 继续循环输入列表,将每个元素添加到该键的列表值中,直到找到另一个带有冒号的元素
  • 冲洗并重复,直到所有元素都以这种方式处理完毕

其他例子是:

inp = ["test:", "one", "help:", "two", "three", "four"]
out = {"test": ["one"], "help": ["two", "three", "four"]
---
inp = ["one:", "list", "two:", "list", "list", "three:", "list", "list", "list"]
out = {"one": ["list"], "two": ["list", "list"], "three": ["list", "list", "list"]}

这感觉应该相对简单(尽管可能不是一句台词!),但我就是无法理解它。

任何建议表示赞赏。

python python-3.x
2个回答
0
投票

不需要任何递归,只需一项一项地取出,如果有冒号则更改键:

inp = ['arg1:', 'list', 'of', 'args', 'arg2:', 'other', 'list']

out = {}
key = None # default key

for item in inp:
    if item.endswith(':'):
        key = item
        continue
    out.setdefault(key, []).append(item)

输出:

{'arg1:': ['list', 'of', 'args'], 'arg2:': ['other', 'list']}

0
投票

我不清楚你如何实现这个递归

您在寻找这样的东西吗?

d = {}
for i in inp:
    if i.endswith(':'):
        k = re.replace(':$', '', k)
        continue
    d[k] = [i] if k not in d else d[k] + [i]
© www.soinside.com 2019 - 2024. All rights reserved.