我有一个包含字符串和列表的列表。我应该告诉你;
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)
基本上,如果值是一个字符串,那么一个新的空列表被添加到dict,如果它是一个列表,它将被附加到前一个列表。
这是使用dictionary comprehension和generator expression结合*
unpacking的一种方式。
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)))}