2015-05-14 58 views
2

我有类型的字典列表:如何高效地搜索列表中的项目?

[ 
    {"num": 60, "name": "A"}, 
    {"num": 50, "name": "B"}, 
    {"num": 49, "name": "C"}, 
    ... etc 
] 

,并列出创建这样的:

[[x, {}] for x in xrange(0, mylist[0]['num'])] 

list: 

[..., [50, {}], [51, {}], ... , [60, {}], ..., [65, {}], ... etc] 

而且我会得到这样的:

[..., [50, {"num": 50, "name": "B"}], [51, {}], ..., [60, {"num": 60, "name": "A"}], ..., [65, {}], ... etc] 

怎么办呢?

回答

1

在你的问题,你写

而且我会得到这样的:
[..., [50, {"num": 50, "name": "B"}], [51, {}], ..., [60, {"num": 60, "name": "A"}]

接受的答案给你不同的东西,所以我想答案更忠实添加到您的原始请求。

这个答案是基于你写下xrange(0, mylist[0]['num'])的观察结果,这让我认为列表中最顶端的数字处于第一位,并且对示例数据的进一步检查表明实际上数字是按递减顺序给出的。 ..所以我最终认为在原始列表中有一个命令。

基于这个假设,这里是我的代码

# data source 
l0 = [{"num": 60, "name": "A"}, {"num": 50, "name": "B"}, {"num": 49, "name": "C"}] 

# initialization, length of data source, void data destination, 
# start from beginning of data source 
ll0, l1, nl = len(l0), [], 0 

# the loop is downwards, because we want to match the numbers 
# in data source from high to low 
for n in range(l0[0]['num'], 0, -1): 
    # first test avoids IndexError, second test is your condition 
    if nl < ll0 and l0[nl]['num'] == n: 
     l1.append([n, l0[nl]]) 
     # if we had a match, we switch our attention to the next item 
     # in data source, hence increment the index in data source 
     nl += 1 
    else: 
     l1.append([n, {}]) 

# we built the data destination list from top to bottom, 
# you want from bottom to top, hence 
l1.reverse() 

重复自己,这个代码假定一个特定的顺序在您的数据源,如果这个假设不成立,我会更乐意退休我的答案。

5

你也可以遍历列表,并得到一个简单的索引相对数量:

>>> [[k['num'],k] for k in li] 
[[60, {'num': 60, 'name': 'A'}], [50, {'num': 50, 'name': 'B'}], [49, {'num': 49, 'name': 'C'}]] 

如果你想与空字典清单丢失,你可以使用列表理解像以下,例如NUMS:

>>> l=[2,3,6,10] 
>>> z=zip(l,l[1:]) 
>>> [t for i,j in z for t in range(i,j)]+[l[-1]] 
[2, 3, 4, 5, 6, 7, 8, 9, 10]