Python 如何使用索引列表为包含多个列表的字典编制索引?

Python 如何使用索引列表为包含多个列表的字典编制索引?,python,list,dictionary,python-2.7,indexing,Python,List,Dictionary,Python 2.7,Indexing,我使用的是Python 2.7.3。 如果我有一本列表词典,比如: >>> x1 = [1,2,3,4,5,6,7,8,5] >>> x2 = range(11,20) >>> mydict = {'first':x1,'second':x2} >>> ind = [0,1,2,3,4,5,6,7] >>> mydict['second'][ind] TypeError: list indices mu

我使用的是Python 2.7.3。 如果我有一本列表词典,比如:

>>> x1 = [1,2,3,4,5,6,7,8,5]
>>> x2 = range(11,20)
>>> mydict = {'first':x1,'second':x2}
>>> ind = [0,1,2,3,4,5,6,7]
>>> mydict['second'][ind]
TypeError: list indices must be integers, not set
>>> import numpy as np
>>> ux1 = np.unique(x1, return_index = True)
。。。而且列表大小相等

>>> len(mydict['second']) == len(mydict['first'])
True
如何使用如下索引列表:

>>> x1 = [1,2,3,4,5,6,7,8,5]
>>> x2 = range(11,20)
>>> mydict = {'first':x1,'second':x2}
>>> ind = [0,1,2,3,4,5,6,7]
>>> mydict['second'][ind]
TypeError: list indices must be integers, not set
>>> import numpy as np
>>> ux1 = np.unique(x1, return_index = True)
要从我的字典中的两个列表中获取值?我曾尝试使用“ind”列表进行索引,但无论ind是列表还是元组,都会不断出现如下错误:

>>> x1 = [1,2,3,4,5,6,7,8,5]
>>> x2 = range(11,20)
>>> mydict = {'first':x1,'second':x2}
>>> ind = [0,1,2,3,4,5,6,7]
>>> mydict['second'][ind]
TypeError: list indices must be integers, not set
>>> import numpy as np
>>> ux1 = np.unique(x1, return_index = True)
我意识到列表不是整数,但集合中的每个值都是整数。有没有办法在不迭代循环中的“计数器”的情况下到达x1[ind]和x2[ind]呢

我不知道这是否重要,但我已经有了索引列表,这是我通过查找以下唯一值得到的:

>>> x1 = [1,2,3,4,5,6,7,8,5]
>>> x2 = range(11,20)
>>> mydict = {'first':x1,'second':x2}
>>> ind = [0,1,2,3,4,5,6,7]
>>> mydict['second'][ind]
TypeError: list indices must be integers, not set
>>> import numpy as np
>>> ux1 = np.unique(x1, return_index = True)
您要使用:


您可以使用
操作符.itemgetter

from operator import itemgetter
indexgetter = itemgetter(*ind)
indexed1 = indexgetter(mydict['first'])
indexed2 = indexgetter(mydict['second'])
注意,在我的示例中,
indexed1
indexed2
将是
tuple
实例,而不是
list
实例。另一种方法是使用列表:

second = mydict['second']
indexed2 = [second[i] for i in ind]

太棒了!179行失败,你用3行就解决了。谢谢!