2017-06-09 22 views
1

我想實現一個處理以下數據的函數:'d'並生成'L'。如何實現?python如何實現以下數據格式轉換?

def func(**d): 
    'do something' 
    return [....] 

源:

d = {'a': 1, 'b': 2, 'c': [3, 4, 5]} 

d = {'a': 1, 'b': 2, 'c': [3, 4, 5], 'd': [6, 7]} 

TO:

L=[{'a':1,'b':2,'c':3}, 
    {'a':1,'b':2,'c':4}, 
    {'a':1,'b':2,'c':5}] 

L=[{'a': 1, 'b': 2, 'c': 3, 'd': 6}, 
    {'a': 1, 'b': 2, 'c': 3, 'd': 7}, 
    {'a': 1, 'b': 2, 'c': 4, 'd': 6}, 
    {'a': 1, 'b': 2, 'c': 4, 'd': 7}, 
    {'a': 1, 'b': 2, 'c': 5, 'd': 6}, 
    {'a': 1, 'b': 2, 'c': 5, 'd': 7}] 

回答

0

這將巨蟒-3工作:

d = {'a': 1, 'b': 2, 'c': [3, 4, 5]} 
def f(**d): 
    return [{**d, 'c': i} for i in d.pop('c')] 
0
d = {'a': 1, 'b': 2,' c': [3, 4, 5]} 

temp_d = d 
L = [] 
for key in temp_d: 
    item = {} 
    for key in temp_d: 
     if isinstance(temp_d[key], list): 
     item[key] = temp_d[key].pop(0) 
     else: 
     item[key] = temp_d[key] 
    L.append(item) 

基本上,我在做什麼這裏是:

  • 我創建字典的副本 'D' 命名' temp_d「;
  • 我檢查'temp_d'字典中的每個鍵,並創建一個空的鍵;
  • 我再次通過'd'字典中的所有鍵循環,基本上我驗證循環的當前鍵的值是否爲列表,如果是,則將該鍵添加到字典'item'中列表的第一個值,帶有函數pop(index)(該函數從列表中移除一個元素並返回它)。如果當前鍵的值不是一個列表,它只是將該鍵的值與該值相加。
  • 填完字典'item'後,我將它附加到'L'。

實施例在這種情況下:

first key ('a'): 
    item = {} 

    first key of second loop ('a'): 
    is the value of 'a' a list? 
    no. adds the value. 
    new item{'a': 1} 

    second key of second loop ('b'): 
    is the value of 'b' a list? 
    no. adds the value. 
    new item{'a': 1, 'b': 2} 

    third key of second loop ('c'): 
    is the value of 'c' a list? 
    yes. adds the first element of the list, removing it from the list 
    (the list was [3, 4, 5], now is [4, 5]) 
    new item{'a': 1, 'b': 2, 'c': 3} 

    appends the item to L 
    (the 'L' was [], now is [{'a': 1, 'b': 2, 'c': 3}]) 

等等,直到結束。

from itertools import cycle 

def func(indict): 
    dictlist = [dict(indict)] # make copy to not change original dict 
    for key in indict: # loop keys to find lists 
     if type(indict[key]) == list: 
      listlength = len(indict[key]) 
      dictlist = listlength * dictlist # elements are not unique 
      for dictindex, listelement in zip(range(len(dictlist)), cycle(indict[key])): 
       dictlist[dictindex] = dict(dictlist[dictindex]) # uniquify 
       dictlist[dictindex][key] = listelement # replace list by list element 
    return dictlist 

在一般情況下,你可以有多個列出你的字典:

0

你的問題可以如下解決。我的解決方案假定你想展開所有這些。

查看解決方案的詳細信息,它首先將原始字典的副本添加到dictlist,然後循環查找元素,並在找到列表時將其與所找到列表的長度相乘dictlist。這將確保dictlist包含正確數量的元素。

但是,元素不會是唯一的,因爲它們將引用相同的底層字典。

爲了解決這個問題,該字典列表的元素是通過循環列表,並用其自身的副本,並在原始indict列表替換每個元件通過列表中的每個元素取代,循環所述不同的「uniquified」 dictlist的元素。

我知道我的解釋有點混亂。對此我很抱歉,但我覺得很難用簡短的方式解釋。

此外,列表中元素的順序與您在問題中要求的順序不同。由於字典的單個鍵 - 值對沒有排序,所以不可能確定元素將被展開的順序,這導致列表順序也得不到保證。