[英]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)
我怎么解决呢?
正如其他评论所提到的,你不能在这里使用字典,因为密钥必须是唯一的。 您需要返回一个列表:
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
后1
。 但是,由于您没有明确问题的所有方面,根据您的需要,您可以使用正确的正则表达式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.