【发布时间】:2019-05-27 12:41:23
【问题描述】:
我正在使用将 json 列表与我的 python 文件中的列表进行比较的代码,但是我使用的 for 循环返回 TypeError: 'function' object is not iterable。我不知道如何解决这个问题
我尝试将“for k2 in occupants:”更改为“for k2 in occupants():”和“for k2 in occupants[:]:”,但这些都有问题
url = 'http://api.open-notify.org/astros.json'
response = urllib.request.urlopen(url)
result = json.loads(response.read())
people = result["people"]
people_with_exist_state = []
occupants = [
{
'name': "Oleg Kononenko",
'bio': 'Oleg Dmitriyevich Kononenko is a Russian cosmonaut. He has flown to the International Space Station four times as a flight engineer and commander. Kononenko accumulated over 533 days in orbit during his first three long duration flights to ISS.',
'img': 'https://upload.wikimedia.org/wikipedia/commons/thumb/a/a0/Kononenko.jpg/220px-Kononenko.jpg',
},
{
'name': "David Saint-Jacques",
'bio': "David Saint-Jacques (born January 6, 1970) is a Canadian astronaut with the Canadian Space Agency (CSA). He is also an astrophysicist, engineer, and a physician.",
'img': 'https://upload.wikimedia.org/wikipedia/commons/thumb/f/f8/David_Saint-Jacques_official_portrait.jpg/440px-David_Saint-Jacques_official_portrait.jpg',
}, #countinues for all occupants of the ISS
@app.route("/occupants")
def occupants():
for k in people:
is_here = 0
for k2 in occupants:
if k['name'] == k2['name']:
is_here = 1
if is_here == 0:
#name does not exist
k['exist'] = 0
else:
# name exist
k['exist'] = 1
people_with_exist_state.append(k)
return render_template('occupants.html', people=people_with_exist_state)
【问题讨论】:
-
您是否通过将变量 occupants 分配给函数来覆盖它?
-
您需要准确地再现缩进。严重缩进的 Python 代码是无稽之谈。