Python 如何有效地搜索列表中的项目?

Python 如何有效地搜索列表中的项目?,python,Python,我有一份目录: [ {"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]

我有一份目录:

[
    {"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]
我会得到这样的结果:

[[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]

如何做到这一点?

您可以在列表上循环,通过简单的索引获得相对编号:

>>> [[k['num'],k] for k in li]
[[60, {'num': 60, 'name': 'A'}], [50, {'num': 50, 'name': 'B'}], [49, {'num': 49, 'name': 'C'}]]
如果希望列表中包含空字典以查找缺少的NUM,可以使用如下列表理解,例如:

>>> 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]

在你的问题中,你写道

我会得到这样的结果:
[…,[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()
#数据源
l0=[{“num”:60,“name”:“A”},{“num”:50,“name”:“B”},{“num”:49,“name”:“C”}]
#初始化、数据源长度、无效数据目标、,
#从数据源的开头开始
ll0,l1,nl=len(l0),[],0
#循环是向下的,因为我们想要匹配数字
#在数据源中从高到低
对于范围内的n(l0[0]['num'],0,-1):
#第一个测试避免索引器,第二个测试是您的条件
如果nl
重复一下,这段代码假设您的数据源中有一个特定的顺序,如果这个假设不成立,我将非常乐意收回我的答案