我正在尝试将多个列表添加到一个字典中,但是看起来它正在打印循环中的最后一个条目。有什么想法可以避免吗?
list_orbited_planet = ["Earth", "Mars", "Pluto", "Uranus"]
low = ["Earth", "Mars", "Mars", "Uranus"]
high = ["Pluto", "Pluto", "Uranus"]
entities = {'low': low, 'high': high}
listPlanets = []
for i in range(len(list_orbited_planet)):
entities['low'] = low.count(list_orbited_planet[i])
entities['high'] = high.count(list_orbited_planet[i])
orbited_planet = {list_orbited_planet[i]: entities}
print(orbited_planet)
listPlanets.append(orbited_planet)
print(listPlanets)
我希望我的输出是这样的:
[{'Earth': {'low': 1, 'high': 0}}, {'Mars': {'low': 2, 'high': 0}}, {'Pluto': {'low': 0, 'high': 2}}, {'Uranus': {'low': 1, 'high': 1}}]
但是,它仅在每个值中显示天王星值,因此从字面上看,低= 1,高= 1。
我想比以前的答案更进一步,并提供一些建议:
for i in range
简单的循环for planet in planets
?(更具可读性)这可以给你这样的东西:
list_orbited_planet = ["Earth", "Mars", "Pluto", "Uranus"]
low = ["Earth", "Mars", "Mars", "Uranus"]
high = ["Pluto", "Pluto", "Uranus"]
listPlanets = []
for planet in list_orbited_planet:
orbited_planet = {
planet:
{
'low': low.count(planet),
'high': high.count(planet)
}
}
listPlanets.append(orbited_planet)
print(listPlanets)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句