Get first element of sublist as dictionary key in python
我看了看,但没有找到答案(我对python还很陌生)。
问题很简单。我有一个由子列表组成的列表:
1 2 | ll [[1,2,3], [4,5,6], [7,8,9]] |
我要做的是创建一个字典,它将每个子列表的第一个元素作为键,并将协同响应子列表的值作为值,例如:
1 | d = {1:[2,3], 4:[5,6], 7:[8,9]} |
号
我该怎么做?
使用字典理解(针对python 2.7+)和切片-
1 | d = {e[0] : e[1:] for e in ll} |
演示-
1 2 3 4 | >>> ll = [[1,2,3], [4,5,6], [7,8,9]] >>> d = {e[0] : e[1:] for e in ll} >>> d {1: [2, 3], 4: [5, 6], 7: [8, 9]} |
使用听写理解:
1 | {words[0]:words[1:] for words in lst} |
输出:
1 | {1: [2, 3], 4: [5, 6], 7: [8, 9]} |
你可以这样做:
1 2 3 4 5 | ll = [[1,2,3], [4,5,6], [7,8,9]] dct = dict( (item[0], item[1:]) for item in ll) # or even: dct = { item[0]: item[1:] for item in ll } print(dct) # {1: [2, 3], 4: [5, 6], 7: [8, 9]} |
主题的另一个变化:
1 | d = {e.pop(0): e for e in ll} |