使用列表项将列表项转换为字典

Converting list items to dictionary using lists items

我有这样的输入数据:

b = [1, 2, 2, 2, 0, 0, 1, 2, 2, 2, 2, 0, 1, 2, 0]
b = map(str, b)

我需要得到这样的结果:

c = { '1': ['2','2','2'], '1': ['2','2','2','2'], '1': ['2'] }

我被这样的步骤卡住了:

c = {}
last_x = []
for x in b:
    while x == '1' or x == '2':
        if x == '1':
            last_x.append(x)
            c.update({x: []})
            break
        elif x == '2':
            c[last_x[-1]].append(x)

我该如何解决?

如其他评论所述,您不能在此处使用字典,因为键必须是唯一的。您需要 return 一个列表:

b = [1, 2, 2, 2, 0, 0, 1, 2, 2, 2, 2, 0, 1, 2, 0]
b = map(str, b)

c = []
for x in b:
    # if it's a '1', create a new {key:list} dict
    if x == '1':
        c.append({x: []})
        k = x
        continue
    # if it's a '2', append it to the last added list
    # make sure to check that 'c' is not empty
    if x == '2' and c:
        c[-1][k].append(x)
>>> print c
>>> [{'1': ['2', '2', '2']}, {'1': ['2', '2', '2', '2']}, {'1': ['2']}]

因为您已经在 b 中将列表转换为字符串,所以您可以使用 regex 来达到这个目的:

>>> import re
>>> [{'1':i} for i in re.findall(r'1(2+)',''.join(b))]
[{'1': '222'}, {'1': '2222'}, {'1': '2'}]

''.join(b) 加入列表 b 的元素所以你将有 :

'122200122220120'

然后你可以使用 re.findall()r'1(2+)' 作为匹配 1 之后每个或多个 2 的模式。但由于您没有阐明问题的所有方面,您可以根据需要使用适当的正则表达式。