发布于2019-08-08 11:13 阅读(479) 评论(0) 点赞(1) 收藏(5)
嵌套 ?
一系列字典存储在列表or列表作为值存储在字典or字典中套字典
alien_0 = {'color': 'green', 'points': 5} alien_1 = {'color': 'yellow', 'points': 10} alien_2 = {'color': 'red', 'points': 15} aliens = [alien_0, alien_1, alien_2] for alien in aliens: print(alien)
这样手动一个一个输入太费劲,让其自动生成多个:
aliens = [] # 生成30个 for alien_number in range(30): new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'} aliens.append(new_alien) # 显示前5个 for alien in aliens[:5]: print(alien)
但此时生成的数量是很多了,可都具有一样的特征,怎么办呢?
for alien in aliens[0:3]:
if alien['color'] == 'green':
alien['color'] = 'yellow'
alien['speed'] = 'medium'
alien['point'] = 10
elif alien['color'] == 'yellow':
alien['color'] = 'red'
alien['speed'] = 'fast'
alien['point'] = 15
通过切片修改部分外星人的特征,就可生成具有不同特征的外星人。
# 存储披萨的信息 pizza = { 'crust': 'thick', 'toppings': ['mushrooms', 'extra cheese'], } # 概述所点的披萨 print("You ordered a " + pizza['crust'] + "-crust pizza with the following toppings:") for topping in pizza['toppings']: print(topping)
多个键值对时:
favorite_languages = { 'jen': ['python', 'ruby'], 'sarah': ['c'], 'edward': ['ruby', 'go'], 'phil': ['python', 'haskell'], } for name, languages in favorite_languages.items(): print("\n" + name.title() + "'s favorite languages are: ") for language in languages: print("\t" + language.title())
运行结果:
Jen's favorite languages are: Python Ruby Sarah's favorite languages are: C Edward's favorite languages are: Ruby Go Phil's favorite languages are: Python Haskell
但有的键只对应一个值,用are表示就有点不妥,可以对此作进一步改进:
for name, languages in favorite_languages.items(): if len(languages) == 1: print("\n" + name.title() + "'s favorite languages is " + languages[0].title() + ".") # 打印出一个键对应一个值的情况 else: print("\n" + name.title() + "'s favorite languages are: ") for language in languages: print("\t" + language.title())
# 存储两个用户各自的一些信息 users = { 'mary': { 'first': 'albert', 'last': 'mary', 'location': 'princeton', }, 'bary': { 'first': 'maria', 'last': 'bary', 'location': 'paris', } } for username, user_info in users.items(): full_name = user_info['first'] + ' ' + user_info['last'] location = user_info['location'] print("\nUsername: " + username) print('\tFull name: ' + full_name.title()) print('\tLocation: ' + location.title())
运行结果:
Username: mary
Full name: Albert Mary
Location: Princeton
Username: bary
Full name: Maria Bary
Location: Paris
作者:我下面给你吃
链接:https://www.pythonheidong.com/blog/article/13548/d46441877d0b8869fd0f/
来源:python黑洞网
任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任
昵称:
评论内容:(最多支持255个字符)
---无人问津也好,技不如人也罢,你都要试着安静下来,去做自己该做的事,而不是让内心的烦躁、焦虑,坏掉你本来就不多的热情和定力
Copyright © 2018-2021 python黑洞网 All Rights Reserved 版权所有,并保留所有权利。 京ICP备18063182号-1
投诉与举报,广告合作请联系vgs_info@163.com或QQ3083709327
免责声明:网站文章均由用户上传,仅供读者学习交流使用,禁止用做商业用途。若文章涉及色情,反动,侵权等违法信息,请向我们举报,一经核实我们会立即删除!