Python 如何获取列表的索引值?
使用以下方法,我能够创建一个值字典:Python 如何获取列表的索引值?,python,list,dictionary,list-comprehension,Python,List,Dictionary,List Comprehension,使用以下方法,我能够创建一个值字典: { p.id : {'total': p.total} for p in p_list} 这将导致{34:{'total:334},53:{'total:123}…} 我还想从列表中列出一个索引,以便知道p.id处于哪个位置。我列了一张这样的清单: c_list = [x for x in range(len(p_list))] { (p,c) for p in p_list for c in c_list} 然后尝试查看如何将c也列为结果的一部
{ p.id : {'total': p.total} for p in p_list}
这将导致{34:{'total:334},53:{'total:123}…}
我还想从列表中列出一个索引,以便知道p.id
处于哪个位置。我列了一张这样的清单:
c_list = [x for x in range(len(p_list))]
{ (p,c) for p in p_list for c in c_list}
然后尝试查看如何将c
也列为结果的一部分。我想我需要这样的东西:
c_list = [x for x in range(len(p_list))]
{ (p,c) for p in p_list for c in c_list}
但是当我尝试实现它时,我无法将c
作为字典中的值:
{ (p.id, c : {'total': p.total, 'position': c}) for p in p_list for c in c_list}
使用
enumerate
从iterable中获取索引和项目:
{ (p.id, ind) : {'id': p.id, 'position': ind} for ind, p in enumerate(p_list)}
更新:
{ p.id : {'id': p.id, 'position': ind} for ind, p in enumerate(p_list)}
有关枚举的帮助信息:
>>> print enumerate.__doc__
enumerate(iterable[, start]) -> iterator for index, value of iterable
Return an enumerate object. iterable must be another object that supports
iteration. The enumerate object yields pairs containing a count (from
start, which defaults to zero) and a value yielded by the iterable argument.
enumerate is useful for obtaining an indexed list:
(0, seq[0]), (1, seq[1]), (2, seq[2]), ...
尝试使用
枚举
。它是一个生成函数,返回形式为:(i,iterable[i])的元组
谢谢你的回答。如果我尝试此操作,我得到一个
键必须是字符串错误。我认为这是因为它试图使用(p.id,ind)
作为字典的键值;我不知道如何避免它。@celenius对我来说很好,元组是dicts的有效键。但是如果你知道索引,为什么要查询字典(使用索引作为元组键的一部分)来获取索引呢P这是我的问题。@ShashankGupta对不起,那是个打字错误。我正在尝试将第一个值作为键dict,我想(p.id,ind)[0]
会起作用吗?@celenius只需使用:p.id:{'id':p.id,'position':ind}
,如果您只想将p.id
作为键。