嗨,我是python的新手,正努力在for循环中创建for循环。我希望底部的三行循环播放。非常感谢!
for restaurant in sorted_list:
wks_res.append_row([
restaurant["name"],
restaurant["rating"],
restaurant["user_ratings_total"],
restaurant['reviews'][0]['text'],
restaurant['reviews'][1]['text'],
restaurant['reviews'][2]['text'],
])
我尝试的方法如下:
for restaurant in sorted_list:
wks_res.append_row([
restaurant["name"],
restaurant["rating"],
restaurant["user_ratings_total"],
for reviews in restaurant['reviews']:
reviews['text'],
])
答案 0 :(得分:3)
这应该有效。当心那些括号,它们是故意重新排列的。在Internet上查看列表理解,以了解有关此的更多信息。
for restaurant in sorted_list:
wks_res.append_row([
restaurant["name"],
restaurant["rating"],
restaurant["user_ratings_total"]] +
[rev["text"] for rev in restaurant["reviews"]]
)
答案 1 :(得分:1)
您不能在表达式内使用for循环。
这应该有效:
for restaurant in sorted_list:
# create the list to append
row = [
restaurant["name"],
restaurant["rating"],
restaurant["user_ratings_total"]
]
# expend this list with 'reviews'
for review in restaurant['reviews']:
row.append(review['text'])
# append the list to wks_res
wks_res.append_row(row)
或者您可以使用list comprehension
row = [
restaurant["name"],
restaurant["rating"],
restaurant["user_ratings_total"]
] + [review['text'] for review in restaurant['reviews']]
答案 2 :(得分:0)
谢谢!这确实有效:
for restaurant in sorted_list:
wks_res.append_row([
restaurant["name"],
restaurant["rating"],
restaurant["user_ratings_total"]] +
[rev["text"] for rev in restaurant["reviews"]]
)