Python 按条目分开列出

Python 按条目分开列出,python,list,Python,List,我知道有一个Python列表,其中包含条目1、2和7,例如 data = [1, 7, 2, 1, 1, 1, 2, 2, 7, 1, 7, 7, 2] 我现在想得到每个条目的所有索引,即 g1 = [0, 3, 4, 5, 9] g2 = [2, 6, 7, 12] g7 = [1, 8, 10, 11] 数据数组可能很长,因此效率很重要。如何实现这一点?您可以使用a来收集每组元素的索引: In [1]: from collections import defaultdict In [2

我知道有一个Python列表,其中包含条目
1
2
7
,例如

data = [1, 7, 2, 1, 1, 1, 2, 2, 7, 1, 7, 7, 2]
我现在想得到每个条目的所有索引,即

g1 = [0, 3, 4, 5, 9]
g2 = [2, 6, 7, 12]
g7 = [1, 8, 10, 11]
数据
数组可能很长,因此效率很重要。如何实现这一点?

您可以使用a来收集每组元素的索引:

In [1]: from collections import defaultdict

In [2]: data = [1, 7, 2, 1, 1, 1, 2, 2, 7, 1, 7, 7, 2]

In [3]: indices = defaultdict(list)

In [4]: for i, d in enumerate(data):
   ...:     indices[d].append(i)
   ...:     

In [5]: indices
Out[5]: defaultdict(<class 'list'>, {1: [0, 3, 4, 5, 9], 2: [2, 6, 7, 12], 7: [1, 8, 10, 11]})
[1]中的
:从集合导入defaultdict
在[2]中:数据=[1,7,2,1,1,1,2,2,7,1,7,2]
在[3]中:索引=defaultdict(列表)
[4]中:对于i,枚举中的d(数据):
…:索引[d]。追加(i)
...:     
在[5]中:索引
Out[5]:defaultdict(,{1:[0,3,4,5,9],2:[2,6,7,12],7:[1,8,10,11]})
您可以使用


像这样更有活力的怎么样

data = [1, 7, 2, 1, 1, 1, 2, 2, 7, 1, 7, 7, 2]
index_dict = {}

for i in range(len(data)):

  # Get or create the entry for the value
  sub_dict = index_dict.setdefault(val, [])

  # Add the index for the value
  sub_dict.append(i)
此代码将为遇到的每个值创建一个条目,并存储其索引。然后您可以查找字典以了解每个值的索引

虽然这段代码没有列表理解那么优雅,但它的优点是只对数据进行一次迭代。

虽然这段代码并不适用于此项工作,但它可以很好地工作:

from werkzeug import MultiDict

data = [1, 7, 2, 1, 1, 1, 2, 2, 7, 1, 7, 7, 2]

g = MultiDict((v, i) for i, v in enumerate(data))
g1 = g.getlist(1)
g2 = g.getlist(2)
g7 = g.getlist(7)

print repr(g7)
# [1, 8, 10, 11]

g={target:[index for index,val in enumerate(data)如果val==target]for set(data)中的目标}
?然后
1
的索引将是
g[1]
。这样,我需要在列表上迭代多次,这在我的应用程序中花费了太长的时间。因此,请使用
g=collections.defaultdict(list)
,然后使用
g[index].append(val)
?你到底试过什么,有什么问题吗?我不知道为什么这个问题有四票接近,因为“不清楚你在问什么”。。。他们读过这个问题吗?我不清楚为什么这个问题被关闭了。我现在删除了“最佳实现”中的“最佳”,因为这并没有增加清晰度,但除此之外,我不确定要更改什么。描述我失败的尝试并不能帮助澄清我认为的问题。就像我的第一个建议一样,这将在
数据上反复多次1。在对
范围的调用中不需要
0
,这是默认值。2.您应该通过标识测试
None
,使用
is
(空列表也是false-y,但肯定可以附加到)。3.您刚刚重写了自己的
defaultdict
,甚至没有使用例如
sub\u dict=index\u dict.get(val,[])
@jornsharpe使用
sub\u dict=index\u dict.get(val,[])
不会在索引目录中创建新条目。不需要使用
进行测试
,因为该条目将始终具有此代码的值,但我还是更新了它
range(len(data))
,你完全正确。@Gab你是对的,对不起-我的意思是
setdefault
,而不是
get
@jornsharpe,我不知道
setdefault
,我的代码现在好多了,谢谢:)
from werkzeug import MultiDict

data = [1, 7, 2, 1, 1, 1, 2, 2, 7, 1, 7, 7, 2]

g = MultiDict((v, i) for i, v in enumerate(data))
g1 = g.getlist(1)
g2 = g.getlist(2)
g7 = g.getlist(7)

print repr(g7)
# [1, 8, 10, 11]