Python初学3-组/序列

组概念

1.列表

列表形式

>>> type([1,2,3,4,5,6])
<type 'list'>
>>> type([1,True,'aaaa'])
<type 'list'>
>>> type([[1,2],[True,'aaa'],[3,'bbb',False]]) //嵌套列表
<type 'list'>

列表获取元素

>>> ['aaa','bbbbb','cccc'][0]
'aaa'
>>> ['aaa','bbbbb','cccc'][0:2]
['aaa', 'bbbbb']
>>> ['aaa','bbbbb','cccc'][0][1]
'a'

列表运算

>>> [1,True,'abc']+['aaa','bbbbb','cccc']
[1, True, 'abc', 'aaa', 'bbbbb', 'cccc']
>>> [1,True,'abc']*2
[1, True, 'abc', 1, True, 'abc']

2.元组

>>> type((1,True,'abc'))
<type 'tuple'>
>>> (1,True,'abc')
(1, True, 'abc')
>>> (1,True,'abc')[0]
1
>>> (1,True,'abc')[0:2]
(1, True)
>>> (1,True,'abc')[2][1]
'b'
<type 'tuple'>
>>> type((1))
<type 'int'>
>>> type(('hello'))
<type 'str'>
>>> type((True))
<type 'bool'>

此时Python将()作为运算符

3.set集合

  特点1:数据类型唯一

>>> type({1,True.'abc'})
SyntaxError: invalid syntax
>>> type({1,2,3})
<type 'set'>

特点2:数据无序

>>> {1,2,3,4}[0]

Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    {1,2,3,4}[0]
TypeError: 'set' object does not support indexing
>>> {1,2,3,4}[0:1]

Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    {1,2,3,4}[0:1]
TypeError: 'set' object has no attribute '__getitem__'
>>> 
特点3:不重复
>>> {1,1,2,2,2,3,3,3,3}
set([1, 2, 3])

集合运算

>>> {1,2,3,4,5,6}-{5,6}
set([1, 2, 3, 4])
>>> {1,2,3,4,5,6}-{5,6,7,8}
set([1, 2, 3, 4])
>>> {1,2,3,4,5,6}&{5,6}
set([5, 6])
>>> {1,2,3,4,5,6}|{5,6}
set([1, 2, 3, 4, 5, 6])
>>> {1,2,3,4,5,6}|{5,6,7,8}
set([1, 2, 3, 4, 5, 6, 7, 8])

空集

>>> type({})
<type 'dict'>
>>> type(set())
<type 'set'>
>>> len(set())
0

4.字典

key(object):value(object)

type({1:1,2:True,3:'abc',True:5,'abc':False})
<type 'dict'>
>>> {1:1,2:True,3:'abc',True:5,'abc':False}[1]
5                        //有问题
>>> {1:1,2:True,3:'abc',True:5,'abc':False}[2]
True
>>> {1:1,2:True,3:'abc',True:5,'abc':False}[3]
'abc'
>>> {1:1,2:True,3:'abc',True:5,'abc':False}[True]
5
>>> {1:1,2:True,3:'abc',True:5,'abc':False}['abc']
False
>>> {1:1,2:True,3:'abc',True:5,'abc':False}['aaaaaaaaa']

Traceback (most recent call last):
  File "<pyshell#15>", line 1, in <module>
    {1:1,2:True,3:'abc',True:5,'abc':False}['aaaaaaaaa']
KeyError: 'aaaaaaaaa'
>>> 



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值