更新dicts位置字段数组

2024-04-23 22:41:42 发布

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

下面的代码用于更新字典数组中的位置值。 当我更新一个对象的位置时,我想根据其他对象的值来更改它们的位置。你知道吗

items = [{'position': 0, '_id': 'Bob'}, {'position': 1, '_id': 'Tom'}, {'position': 2, u'_id': 'Sam'}]
data = {'_id': 'Tom', 'position': 2}

updated_items = []
for item in items:
    if item["_id"] == data["_id"]:
        item["position"] = data["position"]
        updated_items.append(item)
    elif item["position"] < data["position"]:
        updated_items.append(item)
    else:
        item["position"] += 1
        updated_items.append(item)

此代码的输出为:

updated_items = [{'position': 0, '_id': 'Bob'}, {'position': 2, '_id': 'Tom'}, {'position': 3, u'_id': 'Sam'}]

这是意料之中的,也是正确的。但是,如果要更新的对象位于位置0,则输出如下:

items = [{'position': 0, '_id': 'Bob'}, {'position': 1, '_id': 'Tom'}, {'position': 2, u'_id': 'Sam'}]
data = {'_id': 'Bob', 'position': 2}

updated_items = [{'position': 2, '_id': 'Bob'}, {'position': 1, '_id': 'Tom'}, {'position': 3, u'_id': 'Sam'}]

我将如何解决这个问题,并以一种更有效的方式。你知道吗


Tags: 对象代码idfordata字典samposition
1条回答
网友
1楼 · 发布于 2024-04-23 22:41:42

我确实问了一个后续评论,以消除什么类型的输出是可以接受的一些含糊不清。我认为这个问题留下了一些有待解释的问题。下面的代码设计用于处理未排序的列表。它将在要更新的dictitem位置范围和要更改的位置之间对元素重新编号。这个代码将朝着适当的方向移动(这是因为我们可以改变到比原来小或比原来大的位置)。你知道吗

# Update the dictionary list entry matching the id in dictitem with a new position
def updatedictlist(dictlist, dictitem):

    # Get the dict item from the dict list matching the id in dictitem
    upditem = next(item for (index, item) in enumerate(dictlist) if item['_id'] == dictitem['_id'])

    # If there is a StopIteration exception then the dictitem position we 
    # are trying to update TO doesn't exist so we can go ahead and update
    # the dictitem with a new position without making any other changes.
    try:
        dstitem = next(item for (index, item) in enumerate(dictlist) \
                            if item['position'] == dictitem['position'])
    except StopIteration:
        # Update the dictlist and return the list.
        upditem['position'] = dictitem['position']
        return dictlist

    # We only want to update the values between range of values we care about
    # leaving the rest alone.
    rangelow, rangehigh = (min(upditem['position'], dstitem['position']), \
                           max(upditem['position'], dstitem['position']))

    # Since we are replacing a value it matters whether the destination is
    # ahead of us or behind us.
    direction = -1 if upditem['position'] - dstitem['position'] < 0 else 1

    # Shift the values that fall within the position range we are processing
    for item in dictlist:
        if (rangelow <= item['position'] <= rangehigh):
            item['position'] += direction

    # Finally process the dictitem we wanted to update
    upditem['position'] = dictitem['position']

    return dictlist

items = [{'position': 0, '_id': 'Bob'}, {'position': 1, '_id': 'Tom'}, {'position': 2, u'_id': 'Sam'}]
data = {'_id': 'Tom', 'position': 2}
print updatedictlist(copy.deepcopy(items), data)

data = {'_id': 'Bob', 'position': 2}
print updatedictlist(copy.deepcopy(items), data)

输出为:

[{'position': 0, '_id': 'Bob'}, {'position': 2, '_id': 'Tom'}, {'position': 1, u'_id': 'Sam'}]
[{'position': 2, '_id': 'Bob'}, {'position': 0, '_id': 'Tom'}, {'position': 1, u'_id': 'Sam'}]

相关问题 更多 >