如何在python3中使用多个字典追加列表

2024-06-02 06:18:20 发布

您现在位置:Python中文网/ 问答频道 /正文

作为学习的一部分,我不得不使用append函数来添加:

video_ad_1 = {"title": "Healthy Living", "company": "Health Promotion Board", "views": 15934}
video_ad_2 = {"title": "Get a ride, anytime anywhere", "company": "Uber", "views": 923834}
video_ad_3 = {"title": "Send money to your friends with GrabPay", "company": "Grab", "views": 23466}
video_ad_4 = {"title": "Ubereats now delivers nationwide", "company": "Uber", "views": 1337}
video_ad_5 = {"title": "Get cabs now with UberFlash", "company": "Uber", "views": 90234}

在此列表中:

video_ads_list =[]

预期输出应为:

[{'title': 'Healthy Living', 'company': 'Health Promotion Board','views': 15934},
 {'title': 'Get a ride, anytime anywhere', 'company': 'Uber', 'views': 923834},
 .
 .
 {'title': 'Get cabs now with UberFlash', 'company': 'Uber', 'views': 90234}]

问题是我需要使用append函数。你知道吗


Tags: 函数gettitlevideowithnowcompanyad
3条回答

谷歌是我们最好的朋友。根据https://developers.google.com/edu/python/lists

你知道吗列表.append(elem)将单个元素添加到列表的末尾。你知道吗

video_ads_list.append(video_ad_1) 

在这个链接中,你可以找到很多其他有用的方法。试着和他们一起玩。这就是你学习东西的方法

可以在循环中使用append函数。对此的单行解决方案是使用extend

video_ad_1 = {"title": "Healthy Living", "company": "Health Promotion Board", 
"views": 15934} 
video_ad_2 = {"title": "Get a ride, anytime anywhere", "company": "Uber", "views": 
923834} 
video_ad_3 = {"title": "Send money to your friends with GrabPay", "company": "Grab", 
"views": 23466} 
video_ad_4 = {"title": "Ubereats now delivers nationwide", "company": "Uber", 
"views": 1337} 
video_ad_5 = {"title": "Get cabs now with UberFlash", "company": "Uber", "views": 
90234}
video_ads_list =[]
video_ads_list.extend((video_ad_1, video_ad_2, video_ad_3, video_ad_4, video_ad_5))

您可以创建一个列表:

video_ads_list=[video_ad_1,video_ad_2,video_ad_3,video_ad_4,video_ad_5]

还是最好的:

video_ads_list=[globals()['video_ad_%d'%i] for i in range(1,6)]

相关问题 更多 >