[英]compare elements of a list one by one in python
so I want to write a simple code to compare elements of a list one by one. 所以我想编写一个简单的代码来比较列表中的元素。
I defined a simple list with dictionary elements and try following: 我定义了一个包含字典元素的简单列表,然后尝试执行以下操作:
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())
but there is no stage with i = {'price': 55, 'distance': 10} and j = {'price': 55, 'distance': 13} and result of my code is: 但没有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}]
I expected to see 'this' at the result and remove for example the dictionary {'price': 55, 'distance': 13}. 我希望在结果中看到“ this”,并删除例如字典{'price':55,'distance':13}。
help me please. 请帮帮我。 thanks.
谢谢。
Seems like you are aware that you shouldn't manipulate the list you're iterating through, but you missed one point: 似乎您知道您不应该操纵要遍历的列表,但是您错过了一点:
y = x
This just makes y
an alias of x
, and any modification to y
is also applied to x
. 这只是使
y
的别名x
,并且任何修改y
也被施加到x
。
Try y = x[:]
or y = x.copy()
or y = list(x)
so y
becomes a copy of x
and can be safely modified in the loop. 尝试
y = x[:]
或y = x.copy()
或y = list(x)
以便y
成为x
的副本,并且可以在循环中安全地对其进行修改。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.