所以我想写一个简单的代码来逐个比较列表中的元素。你知道吗
我定义了一个包含字典元素的简单列表,并尝试以下操作:
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}的stage,我的代码的结果是:
[{'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.copy()
或y = list(x)
,这样y
就变成了x
的副本,可以在循环中安全地修改。你知道吗相关问题 更多 >
编程相关推荐