定期将按键转换为字典

我有一个包含一个字符串和列表的列表。 我应该告诉你;

list_x = ['a', ['j', '1', 'x'], ['k', '2', 'y'], ['a', '3', 'hj'],
          'd', ['b', '4', 'df'], ['c', '5', 'er'], ['d', '6', 'ty'],
          'g', ['e', '7', 'hj'], ['f', '8', 'bv'], ['g', '9', 'sad'],
          'j', ['h', '10', 'kj'], ['i', '11', 'nbv'], ['c', '12', 'uy'],
          'n', ['d', '13', 'ipoas'], ['e', '14', 'fg'], ['f', '15', 'as'], 
          'r', ['g', '16', 'dsad'], ['h', '17', 'fdgdfg'], ['i', '18', 'retrt'],
          'u', ['j', '19', 'qwe'], ['k', '20', 'ytgf'], ['n', '21', 'asmz']]

我想从这个清单中得到一个字典。

dict_x = {'a': [['j', '1', 'x'], ['k', '2', 'y'], ['a', '3', 'hj']],
          'd': [['b', '4', 'df'], ['c', '5', 'er'], ['d', '6', 'ty']],
          'g': [['e', '7', 'hj'], ['f', '8', 'bv'], ['g', '9', 'sad']],
          'j': [['h', '10', 'kj'], ['i', '11', 'nbv'], ['c', '12', 'uy']],
          'n': [['d', '13', 'ipoas'], ['e', '14', 'fg'], ['f', '15', 'as']], 
          'r': [['g', '16', 'dsad'], ['h', '17', 'fdgdfg'], ['i', '18', 'retrt']],
          'u': [['j', '19', 'qwe'], ['k', '20', 'ytgf'], ['n', '21', 'asmz']]}

这是一个简单循环的简单解决方案:

dict_x = {}
for value in list_x:
    if isinstance(value, str):
        dict_x[value] = current_list = []
    else:
        current_list.append(value)

基本上,如果值是一个字符串,那么一个新的空列表被添加到字典中,并且如果它是一个列表,它会被追加到前一个列表中。


这是一种使用词典理解和生成器表达式结合*解包的方法。

res = {i: j for i, *j in (list_x[i:i + 4] for i in range(0, len(list_x), 4))}

# {'a': [['j', '1', 'x'], ['k', '2', 'y'], ['a', '3', 'hj']],
#  'd': [['b', '4', 'df'], ['c', '5', 'er'], ['d', '6', 'ty']],
#  'g': [['e', '7', 'hj'], ['f', '8', 'bv'], ['g', '9', 'sad']],
#  'j': [['h', '10', 'kj'], ['i', '11', 'nbv'], ['c', '12', 'uy']],
#  'n': [['d', '13', 'ipoas'], ['e', '14', 'fg'], ['f', '15', 'as']],
#  'r': [['g', '16', 'dsad'], ['h', '17', 'fdgdfg'], ['i', '18', 'retrt']],
#  'u': [['j', '19', 'qwe'], ['k', '20', 'ytgf'], ['n', '21', 'asmz']]}

或者,如@chrisz所示,您可以使用zip

res = {i: j for i, *j in zip(*(list_x[i::4] for i in range(4)))}
链接地址: http://www.djcxy.com/p/53571.html

上一篇: Convert flat list to dictionary with keys at regular intervals

下一篇: A pythonic way of packing loops into a function to mute variables?