하나의 사전에 여러 목록을 추가하려고하는데 루프의 마지막 항목을 인쇄하는 것처럼 보입니다. 어떻게 피할 수 있습니까?
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] 삭제
몇 마디 만하겠습니다