Python Container Dictionary And List


在我理解看来  dictinary 就是键值对 是可变的  可以增加减少键值对


>>> d={'one'=1,'two'=2}
  File "<stdin>", line 1
    d={'one'=1,'two'=2}
            ^
SyntaxError: invalid syntax
>>> d={'one'=1:'two'=2}
  File "<stdin>", line 1
    d={'one'=1:'two'=2}
            ^
SyntaxError: invalid syntax
>>> d={'one':1,'two':2}
>>> d
{'two': 2, 'one': 1}
>>> dd=dict('three'=3,'four'=4,**d)
  File "<stdin>", line 1
SyntaxError: keyword can't be an expression
>>> dd=dict('three'=3,'four'=4,**d)
  File "<stdin>", line 1
SyntaxError: keyword can't be an expression
>>> dd=dict(three=3,four=4,**d)
>>> dd
{'four': 4, 'one': 1, 'three': 3, 'two': 2}


dict的两种初始话方法

是否包含某个元素

>>> 'four' in dd
True
>>> 'five' in dd
False


遍历

>>> for k,v in dd.items():print(k,v)
... 
four 4
one 1
three 3
two 2


get某个键值 可以如果没有的话可以返回空或者给定默认值

>>> dd.get('five',None)
>>> dd.get('five','5')
'5'
>>> dd.get('five',5)

而这样 没有该元素的话会报错

>>> dd['five']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'five'
>>> dd['one']
1
5
>>> dd.get('five')

获取某个值 并将其从dic中删除

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


若想直接删除

>>> del dd['two']
>>> dd
{'four': 4, 'three': 3}
>>> 



list


>>> l=[1,2,3]
>>> l.extend(range(10))   #添加另外的list
>>> l
[1, 2, 3, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> l.insert(0,11)  #指定下标添加元素
>>> l
[11, 1, 2, 3, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> l.pop(0)   #得到下标元素并去除
11
>>> l.push(12)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'list' object has no attribute 'push'
>>> l.append(12)  # 队尾添加一个元素
>>> l
[1, 2, 3, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 12]
>>> l.remove(12)   #去除值=12的第一个元素
>>> l


[1, 2, 3, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> l.remove(1)
>>> l
[2, 3, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]









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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值