Sky*_*xic 0 python list python-3.8
在下面的脚本中,当第二个循环开始时会发生一些奇怪的事情。area_1即使该列表根本不涉及该循环,该列表也会更改值。area_2在第三个循环之后也会发生同样的情况。
server_1 = 'x1'
server_2 = 'x2'
server_3 = 'x3'
table = [
{'Terminal': 'site_1', 'City': 'London', 'Station': server_1},
{'Terminal': 'site_2', 'City': 'London', 'Station': server_1},
{'Terminal': 'site_3', 'City': 'London', 'Station': server_2},
{'Terminal': 'site_4', 'City': 'New York', 'Station': server_3},
{'Terminal': 'site_5', 'City': 'New York', 'Station': server_1},
{'Terminal': 'site_6', 'City': 'New York','Station': server_2},
{'Terminal': 'site_7', 'City': 'Tokyo', 'Station': server_3},
{'Terminal': 'site_8', 'City': 'Tokyo', 'Station': server_3},
{'Terminal': 'site_9', 'City': 'Tokyo', 'Station': server_2}
]
city_index = [
{'City':'London', 'Lat': 51.48,'Long': -0.14 },
{'City':'New York', 'Lat': 40.69,'Long': -74.26 },
{'City':'Tokyo', 'Lat': 35.51,'Long': 138.64 }
]
area_1 = []
for i in city_index:
area_1.append(i)
area_1[-1].update({'Station': server_1, 'Count of terminals': sum(q['City'] == i['City'] and q['Station'] == server_1 for q in table)})
area_2 = []
for i in city_index:
area_2.append(i)
area_2[-1].update({'Station': server_2, 'Count of terminals': sum(q['City'] == i['City'] and q['Station'] == server_2 for q in table)})
area_3 = []
for i in city_index:
area_3.append(i)
area_3[-1].update({'Station': server_3, 'Count of terminals': sum(q['City'] == i['City'] and q['Station'] == server_3 for q in table)})
all = area_1 + area_2 + area_3
for i in all:
print(i)
Run Code Online (Sandbox Code Playgroud)
输出:(注意电台键)
{'City': 'London', 'Lat': 51.48, 'Long': -0.14, 'Station': 'x3', 'Count of terminals': 0}
{'City': 'New York', 'Lat': 40.69, 'Long': -74.26, 'Station': 'x3', 'Count of terminals': 1}
{'City': 'Tokyo', 'Lat': 35.51, 'Long': 138.64, 'Station': 'x3', 'Count of terminals': 2}
{'City': 'London', 'Lat': 51.48, 'Long': -0.14, 'Station': 'x3', 'Count of terminals': 0}
{'City': 'New York', 'Lat': 40.69, 'Long': -74.26, 'Station': 'x3', 'Count of terminals': 1}
{'City': 'Tokyo', 'Lat': 35.51, 'Long': 138.64, 'Station': 'x3', 'Count of terminals': 2}
{'City': 'London', 'Lat': 51.48, 'Long': -0.14, 'Station': 'x3', 'Count of terminals': 0}
{'City': 'New York', 'Lat': 40.69, 'Long': -74.26, 'Station': 'x3', 'Count of terminals': 1}
{'City': 'Tokyo', 'Lat': 35.51, 'Long': 138.64, 'Station': 'x3', 'Count of terminals': 2}
Run Code Online (Sandbox Code Playgroud)
所有 3 个列表在末尾都变得相同 = area_3。有人可以解释为什么会这样吗?为什么area_1和area_2不被覆盖?
使用copy模块来复制对象而不是引用它们。
import copy
area.append(copy.copy(i))
Run Code Online (Sandbox Code Playgroud)
此外,使用i不是整数的迭代器非常令人困惑,尽量避免它
| 归档时间: |
|
| 查看次数: |
66 次 |
| 最近记录: |