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

2024-04-19 22:51:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用的是python2.7.3。 如果我有一本列表字典,像这样:

>>> x1 = [1,2,3,4,5,6,7,8,5]
>>> x2 = range(11,20)
>>> mydict = {'first':x1,'second':x2}

。。。名单大小相等。。。你知道吗

>>> len(mydict['second']) == len(mydict['first'])
True

如何使用如下索引列表:

>>> ind = [0,1,2,3,4,5,6,7]

从字典中的两个列表中获取值?我曾尝试使用“ind”列表进行索引,但无论ind是列表还是元组,都会不断出现如下错误:

>>> mydict['second'][ind]
TypeError: list indices must be integers, not set

我知道列表不是整数,但是集合中的每个值都是整数。有没有办法不在循环中迭代一个“计数器”就到达x1[ind]和x2[ind]呢?你知道吗

我不知道这是否重要,但我已经有了索引列表,我从中找到了这样的唯一值:

>>> import numpy as np
>>> ux1 = np.unique(x1, return_index = True)

Tags: true列表len字典nprange整数mydict
2条回答

要使用^{}

getter = itemgetter(*ind)
getter(mydict['second']) # returns a tuple of the elements you're searching for.

您可以使用operator.itemgetter

from operator import itemgetter
indexgetter = itemgetter(*ind)
indexed1 = indexgetter(mydict['first'])
indexed2 = indexgetter(mydict['second'])

注意,在我的示例中,indexed1indexed2将是tuple实例,而不是list 实例。另一种方法是使用列表:

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

相关问题 更多 >