从Python中的二维列表创建字典

从Python中的二维列表创建字典,python,list,dictionary,Python,List,Dictionary,我面临着从一个列表和一系列列表创建字典的困难。下面是一个例子: a = ['a','b','c','d'] b = [[1,2,0], [3,4,1], [5,6,0], [7,8,1]] 我想要一个使用lista的元素和listb的第三个元素的输出,如下输出: a = {'a': 0, 'b': 1, 'c': 0, 'd': 1] 两个列表的长度相同,因此我尝试了以下方法: c = dict(zip(a,b)) 但是在这种情况下,我不能选择b的第三个元素 在我的实际案例中,我有数百万的

我面临着从一个列表和一系列列表创建字典的困难。下面是一个例子:

a = ['a','b','c','d']
b = [[1,2,0], [3,4,1], [5,6,0], [7,8,1]]
我想要一个使用lista的元素和listb的第三个元素的输出,如下输出:

a = {'a': 0, 'b': 1, 'c': 0, 'd': 1]
两个列表的长度相同,因此我尝试了以下方法:

c = dict(zip(a,b))
但是在这种情况下,我不能选择b的第三个元素

在我的实际案例中,我有数百万的数据,所以我需要一种快速而简单的方法来完成它,从b创建一个临时列表可能不是一个最佳的解决方案

谢谢

您可以:

dict(zip(a, (x[-1] for x in b)))  # Maybe x[2] if some of the sublists have more than 3 elements.
如果您使用的是python2.x,您可能希望使用
itertools.izip
或您可以执行以下操作:

dict(zip(a, (x[-1] for x in b)))  # Maybe x[2] if some of the sublists have more than 3 elements.

如果您使用的是python2.x,您可能需要使用
itertools.izip
或我已经尝试过这一方法,它似乎很有效:

>>> a = ['a','b','c','d']
>>> b = [[1,2,0], [3,4,1], [5,6,0], [7,8,1]]
>>> c = dict(zip(a, [d[2] for d in b]))
>>> c
{'a': 0, 'c': 0, 'b': 1, 'd': 1}

我试过这个,它似乎很有效:

>>> a = ['a','b','c','d']
>>> b = [[1,2,0], [3,4,1], [5,6,0], [7,8,1]]
>>> c = dict(zip(a, [d[2] for d in b]))
>>> c
{'a': 0, 'c': 0, 'b': 1, 'd': 1}

或者,在理解中使用词典:

a = ['a','b','c','d']
b = [[1,2,0], [3,4,1], [5,6,0], [7,8,1]]

c = {k: v[-1] for k, v in zip(a, b)}

参见Dict理解

或在理解中使用词典:

a = ['a','b','c','d']
b = [[1,2,0], [3,4,1], [5,6,0], [7,8,1]]

c = {k: v[-1] for k, v in zip(a, b)}

参见Dict Comprehensions

您可以在
操作符
模块中使用
itemgetter
。其中2表示b子列表中的索引

from operator import itemgetter
a = ['a','b','c','d']
b = [[1,2,0], [3,4,1], [5,6,0], [7,8,1]]

c = dict(zip(a, map(itemgetter(2), b)))
由于您有很多元素,因此,
itertools
可能有助于提高内存:

from operator import itemgetter
from itertools import izip, imap

a = ['a','b','c','d']
b = [[1,2,0], [3,4,1], [5,6,0], [7,8,1]]

c = dict(izip(a, imap(itemgetter(2), b)))

这些解决方案将有助于利用底层C模块的性能优势。

您可以在
operator
模块中使用
itemgetter
。其中2表示b子列表中的索引

from operator import itemgetter
a = ['a','b','c','d']
b = [[1,2,0], [3,4,1], [5,6,0], [7,8,1]]

c = dict(zip(a, map(itemgetter(2), b)))
由于您有很多元素,因此,
itertools
可能有助于提高内存:

from operator import itemgetter
from itertools import izip, imap

a = ['a','b','c','d']
b = [[1,2,0], [3,4,1], [5,6,0], [7,8,1]]

c = dict(izip(a, imap(itemgetter(2), b)))
这些解决方案将有助于利用底层C模块的性能优势