![](/img/trans.png)
[英]In python, how would I create a dictionary of all unique words listed in a text file. So far I have this code. Thanks
[英]How would I get past this assertion test in Python for trying to find the sum of all the number of views listed in a Dictionary?
我如何通過 Python 中的這個斷言測試來嘗試找到所有視圖數量的總和? 下面是我得到的字典,然后是我試圖通過的斷言測試。 我必須創建一個返回通過斷言的東西的函數。
video_reviews = [
{
"name": "Cats doing nothing",
"number_of_views": 450743,
"reviews": [
{"name": "Jeb", "review": 5},
{"name": "Samantha", "review": 2},
{"name": "Crystal", "review": 3},
]
},
{
"name": "All Fail",
"number_of_views": 1239734,
"reviews": [
{"name": "Crystal", "review": 5},
{"name": "Frank", "review": 3},
{"name": "Jeb", "review": 3},
]
},
{
"name": "Runaway Nintendo",
"number_of_views": 48343,
"reviews": [
{"name": "Samantha", "review": 4},
{"name": "Bill", "review": 3},
{"name": "Sarah", "review": 4},
]
},
]
assert total_by_video(video_reviews, "Runaway Nintendo") == 48343
assert total_by_video(video_reviews, "All Fail") == 1239734
assert total_by_video(video_reviews, "Critters") == 0
video_reviews
是字典列表。 對於單個字典d
您可以獲得這樣的視圖數量: number_of_views=d["number_of_views"]
有了這些知識,您可以使用 for 循環或列表理解來創建僅包含數字的列表。
number_of_views_list = [450743, 1239734, 48343]
現在你所要做的就是總結這個列表。 這也可以通過 for 循環來完成,或者您可以使用sum
函數。
您的函數可能看起來有點像這樣:
def sum_of_views(reviews):
# TODO create number_of_views_list
# TODO sum up number_if_views_list
return result
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.