码迷,mamicode.com
首页 > 其他好文 > 详细

第七章 字典和集合[DDT书本学习 小甲鱼]【1】

时间:2019-01-28 11:00:08      阅读:195      评论:0      收藏:0      [点我收藏+]

标签:nbsp   字符   ddt   height   好用   没有   引号   集合   width   

技术分享图片

7.1 字典 当索引不好用时
a1=["我","你","她"]
a2=["我很好","你很好","她很好"]
print("我要说的是:",a2[a1.index("我")])

7.1.1 创建和访问字典
变成字典形式:
dict1={"我":"我很好","你":"你很好","她":"她很好"}
print(dict1["你"])
--------------------
你很好
===================================
映射关系 字典{} 组成部分由(键:值)
序列类型 列表[] 元组() 字符串""
====================
dict2={1:"one",2:"two",3:"three"}
print(dict2[2])
-------------------
two
=====================
dict3={}
print(dict3)
----------
{}
========================
dict4=dict((("F",70),("i",105),("s",115),("h",104),("c",67)))
print(dict4)
----------------------
{‘F‘: 70, ‘i‘: 105, ‘s‘: 115, ‘h‘: 104, ‘c‘: 67}
====================================================
dict5=dict(我="世界",你="房子",她="火车") #加引号会报错
print(dict5)
---------------------------
{‘我‘: ‘世界‘, ‘你‘: ‘房子‘, ‘她‘: ‘火车‘}
======================================================
给键改值,如果没有该键,【创建】该键和值。
代码如下
dict5=dict(我="世界",你="房子",她="火车") #加引号会报错
dict5["你"]="坦克"
dict5["他们"]="狼群"
print(dict5)
-----------------------------------------
{‘我‘: ‘世界‘, ‘你‘: ‘坦克‘, ‘她‘: ‘火车‘, ‘他们‘: ‘狼群‘}
===========================================================
总结下面5种方法,都可以用来创建字典,仔细体会:
a=dict(one=1,two=2,three=3)
b={"one":1,"two":2,"three":3}
c=dict(zip(["one","two","three"],[1,2,3]))
d=dict([("two",2),("one",1),("three",3)])
e=dict({"one":1,"two":2,"three":3})
print(a)
print(b)
print(c)
print(d)
print(e)
---------------------------------------------
{‘one‘: 1, ‘two‘: 2, ‘three‘: 3}
{‘one‘: 1, ‘two‘: 2, ‘three‘: 3}
{‘one‘: 1, ‘two‘: 2, ‘three‘: 3}
{‘two‘: 2, ‘one‘: 1, ‘three‘: 3}
{‘one‘: 1, ‘two‘: 2, ‘three‘: 3}

 

第七章 字典和集合[DDT书本学习 小甲鱼]【1】

标签:nbsp   字符   ddt   height   好用   没有   引号   集合   width   

原文地址:https://www.cnblogs.com/daodantou/p/10328321.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!