Flask If 语句 - 列表索引的范围
Flask If Statement - Range for list index
customer_data.json(加载为 customer_data)
{
"customers": [
{
"username": "anonymous",
"id": "1234",
"password": "12341234",
"email": "1234@gmail.com",
"status": false,
"books": [
"Things Fall Apart",
"Fairy Tales",
"Divine Comedy"
]
}
]
}
new_catalog.json 中的示例 post。 (加载为 posts)
{
"books": [
{
"author": "Chinua Achebe",
"country": "Nigeria",
"language": "English",
"link": "https://en.wikipedia.org/wiki/Things_Fall_Apart\n",
"pages": 209,
"title": "Things Fall Apart",
"year": 1958,
"hold": false
}
}
Flask_practice.py
中的必要代码
for customer in customer_data['customers']:
if len(customer['books']) > 0:
for book in customer['books']:
holds.append(book)
for post in posts['books']:
if post['title'] == holds[range(len(holds))]:
matching_posts['books'].append(post)
holds[range(len(holds))]
无效。
我正在尝试使用 holds[0], holds[1]
等浏览 holds
中的每一本书,并测试 title
是否等于 [=17= 中的书名].
我对 Flask、Stack Overflow 和一般编码还是个新手,所以这个问题可能有一个非常简单的解决方案。
I am trying to go through each of the books in holds
using holds[0]
, holds[1]
etc and test to see if the title is equal to a book title
几乎直译为 Python:
# For each post...
for post in posts['books']:
# ...go through each of the books in `holds`...
for hold in holds:
# ...and see if the title is equal to a book title
if post['title'] == hold:
matching_posts['books'].append(post)
或者,如果您不想 append(post)
holds
中的每个项目:
for post in posts['books']:
if post['title'] in holds:
matching_posts['books'].append(post)
customer_data.json(加载为 customer_data)
{
"customers": [
{
"username": "anonymous",
"id": "1234",
"password": "12341234",
"email": "1234@gmail.com",
"status": false,
"books": [
"Things Fall Apart",
"Fairy Tales",
"Divine Comedy"
]
}
]
}
new_catalog.json 中的示例 post。 (加载为 posts)
{
"books": [
{
"author": "Chinua Achebe",
"country": "Nigeria",
"language": "English",
"link": "https://en.wikipedia.org/wiki/Things_Fall_Apart\n",
"pages": 209,
"title": "Things Fall Apart",
"year": 1958,
"hold": false
}
}
Flask_practice.py
中的必要代码 for customer in customer_data['customers']:
if len(customer['books']) > 0:
for book in customer['books']:
holds.append(book)
for post in posts['books']:
if post['title'] == holds[range(len(holds))]:
matching_posts['books'].append(post)
holds[range(len(holds))]
无效。
我正在尝试使用 holds[0], holds[1]
等浏览 holds
中的每一本书,并测试 title
是否等于 [=17= 中的书名].
我对 Flask、Stack Overflow 和一般编码还是个新手,所以这个问题可能有一个非常简单的解决方案。
I am trying to go through each of the books in
holds
usingholds[0]
,holds[1]
etc and test to see if the title is equal to a book title
几乎直译为 Python:
# For each post...
for post in posts['books']:
# ...go through each of the books in `holds`...
for hold in holds:
# ...and see if the title is equal to a book title
if post['title'] == hold:
matching_posts['books'].append(post)
或者,如果您不想 append(post)
holds
中的每个项目:
for post in posts['books']:
if post['title'] in holds:
matching_posts['books'].append(post)