Python入门学习P26~P30

目录

字典

集合

文件


字典

1.字典是映射类型,用大括号表示,由多个键值组成,键:key,值:value。

>>> brand=['李宁','耐克','阿迪达斯','小甲鱼']
>>> slogan=['一切皆有可能','Just do it','Impossible is nothing','让编程改变世界']
>>> print('小甲鱼的口号是:',slogan[brand.index('小甲鱼')])
小甲鱼的口号是: 让编程改变世界
>>> dict1={'李宁':'一切皆有可能','耐克':'Just do it','阿迪达斯':'Impossible is nothing','小甲鱼':'让编程改变世界'}
>>> print('小甲鱼的口号是:',dict1['小甲鱼'])
小甲鱼的口号是: 让编程改变世界
>>> dict2={1:'one',2:'two',3:'three'}
>>> dict2[2]
'two'
>>> dict3=dict((('F',70),('i',105),('s',115),('h',104),('C',67)))
>>> dict3
{'F': 70, 'i': 105, 's': 115, 'h': 104, 'C': 67}
>>> dict4=dict(小甲鱼='让编程改变世界',耐克='Just do it')
>>> dict4
{'小甲鱼': '让编程改变世界', '耐克': 'Just do it'}
>>> dict4['小甲鱼']
'让编程改变世界'
>>> dict4['爱迪生']='天才就是99%的汗水+%1灵感,但这1%的灵感远比99%的汗水更重要'
>>> dict4
{'小甲鱼': '让编程改变世界', '耐克': 'Just do it', '爱迪生': '天才就是99%的汗水+%1灵感,但这1%的灵感远比99%的汗水更重要'}
>>> 

2.fromkeys()

>>> dict1={ }
>>> dict1.fromkeys ((1,2,3))
{1: None, 2: None, 3: None}
>>> dict1.fromkeys ((1,2,3),'number')
{1: 'number', 2: 'number', 3: 'number'}
>>> dict1.fromkeys ((1,2,3),('one','two','three'))
{1: ('one', 'two', 'three'), 2: ('one', 'two', 'three'), 3: ('one', 'two', 'three')}
>>> dict1=dict1.fromkeys (range(6),'hello')
>>> dict1
{0: 'hello', 1: 'hello', 2: 'hello', 3: 'hello', 4: 'hello', 5: 'hello'}

3.访问字典中的项:get方法,dict1.get (7)。

4.清空一个字典:clear(),不要直接dict1={ }。

 5.全拷贝copy(),查看地址id()。

>>> a={1:'one',2:'two',3:'three'}
>>> b=a.copy()
>>> c=a
>>> c
{1: 'one', 2: 'two', 3: 'three'}
>>> a
{1: 'one', 2: 'two', 3: 'three'}
>>> b
{1: 'one', 2: 'two', 3: 'three'}
>>> id(a)
1976148756416
>>> id(b)
1976148755968
>>> id(c)
1976148756416
>>> c[4]='four'
>>> c
{1: 'one', 2: 'two', 3: 'three', 4: 'four'}
>>> a
{1: 'one', 2: 'two', 3: 'three', 4: 'four'}
>>> b
{1: 'one', 2: 'two', 3: 'three'}

6.pop()是给一个键,把这个键对应的值弹出去,popitem()是随机弹出一个值。

>>> a.pop(2)
'two'
>>> a
{1: 'one', 3: 'three', 4: 'four'}
>>> a.popitem ()
(4, 'four')
>>> a
{1: 'one', 3: 'three'}

7.setdefault()和get()方法类似,如果键不存在就添加一个新的键。

8.a.update(b)把字典b的键值更新到字典a里。

>>> a.setdefault ('小白')
>>> a
{1: 'one', 3: 'three', '小白': None}
>>> a.setdefault (5,'five')
'five'
>>> a
{1: 'one', 3: 'three', '小白': None, 5: 'five'}
>>> b={'小白':'狗'}
>>> a.update(b)
>>> a
{1: 'one', 3: 'three', '小白': '狗', 5: 'five'}

集合

9.集合set:{1,2,3,4,5},集合中的所有元素具有唯一性,重复的被自动剔除,集合中的元素是无序的,不支持索引。

10.要添加一个元素到集合中:num1.add(6)。

11.要移除一个元素:num1.remove(5)。

12.不可变集合:frozenset。

文件

 13.文件:

(下表有的不对) 

 

 打开文件:f=open('D:\\record.txt',encoding='UTF-8')

读取整个文件:f.read(),加参数表述读取几个字节。

读取一行:f.readline(),加参数表述读取几个字节。

 就先这些,有用到的再补充吧。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值