如何在python 3中使用多个词典追加列表

问题描述 投票:-2回答:3

作为我学习的一部分,我不得不使用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函数。

python append
3个回答
0
投票

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

list.append(elem) - 在列表末尾添加一个元素。

video_ads_list.append(video_ad_1) 

在链接中,您可以找到许多其他有用的列表方法。尝试和他们一起玩。这是你学习东西的方式


0
投票

您可以在循环中使用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))

0
投票

您可以创建一个列表:

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)]
© www.soinside.com 2019 - 2024. All rights reserved.