在python中获取子列表的第一个元素作为字典键

mat*_*teo 3 python dictionary list sublist

我看了,但我没有找到答案(我对python很新).

问题很简单.我有一个由子列表组成的列表:

ll
[[1,2,3], [4,5,6], [7,8,9]]
Run Code Online (Sandbox Code Playgroud)

我要做的是创建一个字典,其中每个子列表的第一个元素都是关键字,并且值为相应的子列表的值,如:

d = {1:[2,3], 4:[5,6], 7:[8,9]}
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?

Ana*_*mar 7

使用字典理解(适用于Python 2.7 +)和切片 -

d = {e[0] : e[1:] for e in ll}
Run Code Online (Sandbox Code Playgroud)

演示 -

>>> 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]}
Run Code Online (Sandbox Code Playgroud)


The*_*nse 5

使用dict理解

{words[0]:words[1:] for words in lst}
Run Code Online (Sandbox Code Playgroud)

输出:

{1: [2, 3], 4: [5, 6], 7: [8, 9]}
Run Code Online (Sandbox Code Playgroud)