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

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

给出以下列表:

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
4个回答
1
投票

不需要任何递归,只需一项一项地取出项目即可,如果有冒号则更改密钥。使用

dict.sedefault
作为助手来初始化空列表:

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

1
投票

我不相信有一种“Pythonic”的方法可以做到这一点,而不使用一些 lambda 表达式,这会使代码变得不可读。

但是正如您所指出的,使用循环来实现这一点非常简单,并“利用”

dict
是可变的事实:

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

result = {}
reference_point = result
for item in inp:
    if item.endswith(':'):
        if (item := item.rstrip(':')) not in result:
            result[item] = []

        reference_point = result[item]
    else:
        reference_point.append(item)

print(result)

有一些边缘情况我没有考虑到,主要是因为您没有指定在这种情况下应该发生什么。就像如果输入以“值”开头而不是以

:
结尾的项目一样。

但这应该能让您大致了解如何解决它。


0
投票
import itertools


L = ["arg1:", "list", "of", "args", "arg2:", "other", "list"]
answer = {}
key = None
for k, group in itertools.groupby(L, lambda s: s.endswith(":")):
    if k:
        key = list(group)[0]
    else:
        answer[key] = list(group)

结果:

In [313]: answer
Out[313]: {'arg1:': ['list', 'of', 'args'], 'arg2:': ['other', 'list']}

-1
投票

我不清楚你如何使其递归

您在寻找这样的东西吗?

d = {}
for i in inp:
    if i.endswith(':'):
        k = re.sub(':$', '', i)
        continue
    d[k] = [i] if k not in d else d[k] + [i]
# {'arg1': ['list', 'of', 'args'], 'arg2': ['other', 'list']}
© www.soinside.com 2019 - 2024. All rights reserved.