在 python 中逐一比较列表的元素

compare elements of a list one by one in python

所以我想写一个简单的代码来逐个比较列表中的元素。

我定义了一个包含字典元素的简单列表并尝试执行以下操作:

x = [{'price': 66, 'distance': 1}, {'price': 63, 'distance': 2} \
    , {'price': 64, 'distance': 3}, {'price': 75, 'distance': 5}, \
     {'price': 75, 'distance': 10}, {'price': 60, 'distance': 10}, \
     {'price': 50, 'distance': 10}, {'price': 55, 'distance': 13},\
     {'price': 63, 'distance': 2}]

def nested_skyline():
    y = x
    for i in x:
        for j in x:
            if i != j:
                if i == {'price': 55, 'distance': 10} and j == {'price': 55, 'distance': 13}:
                    print('this')
                if (i['price'] == j['price']) and (i['distance'] < j['distance']):
                    y.remove(j)
                elif (i['price'] < j['price']) and (i['distance'] <= j['distance']):
                    y.remove(j)

    return y

if __name__ == '__main__':
    print(nested_skyline())

但是没有 i = {'price': 55, 'distance': 10} 和 j = {'price': 55, 'distance': 13} 的阶段我的代码的结果是:

[{'price': 66, 'distance': 1}, {'price': 63, 'distance': 2}, {'price': 60, 'distance': 10}, {'price': 50, 'distance': 10}, {'price': 55, 'distance': 13}, {'price': 63, 'distance': 2}]

我希望在结果中看到 'this' 并删除例如字典 {'price': 55, 'distance': 13}.

请帮助我。 谢谢。

您似乎意识到不应该操纵正在迭代的列表,但您错过了一点:

y = x

这只会使 y 成为 x 的别名,对 y 的任何修改也会应用于 x

尝试 y = x[:]y = x.copy()y = list(x) 这样 y 成为 x 的副本并且可以在循环中安全地修改。