2015-02-06 99 views
3

我有這樣的輸入數據:轉換列表項使用列表項字典

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) 

我該如何解決它?

+0

爲什麼'c'字典沒有任何鍵的字典?你確定這是你想要的輸出嗎? – matsjoyce 2015-02-06 09:43:06

+0

@matsjoyce固定 – 2015-02-06 09:47:03

+4

錯誤,現在你有重複的密鑰。 – matsjoyce 2015-02-06 09:47:31

回答

1

正如其他意見所述,您不能在這裏使用字典,因爲密鑰必須是唯一的。你需要返回一個列表:

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

當你有你的列表轉換爲字符串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。但由於您沒有澄清問題的所有方面,根據您的需要,您可以使用適當的正則表達式。