python的对象模型_01_Python常见对象模型

python的对象模型,也是其基本的数据结构

一、Python最基础的数据结构开始:元组、列表、字典和集合

1、元组(tuple)对象

(1)创建元组:

1)

>>>tup = 4, 5, 6

>>>tup

(4, 5, 6)

>>>nexted_tup = (4, 5, 6), (1, 2)

>>>nexted_tup

((4, 5, 6), (1, 2))

2)用tuple可以将任意序列或迭代器转换成元组

>>>tuple([9, 4, 2, 0])

(9, 4, 2, 0)

>>>tuple('string')

('s', 't', 'r', 'i', 'n', 'g')

(2)访问元组:

# 从0开始

>>>tup = tuple('string')

>>>tup[0]

's'

>>>tup = tuple('fool', [5, 2, 0], True)

Traceback (most recent call last):

File "", line 1, in

tup = tuple('fool', [5, 2, 0], True)

TypeError: tuple expected at most 1 argument, got 3

# 不可变对象

>>>tup = tuple(['fool', [5, 2, 0], True])

# tuple对象不可变

>>>tup[2]=False

Traceback (most recent call last):

File "", line 1, in

tup[2]=False

TypeError: 'tuple' object does not support item assignment

# tuple的对象是可变对象,则可原位改变

>>>tup[1].append(5)

>>>tup

('fool', [5, 2, 0, 5], True)

# 但是不能改变

>>>tup[1]=[0, 2, 5]

Traceback (most recent call last):

File "", line 1, in

tup[1]=[0, 2, 5]

TypeError: 'tuple' object does not support item assignment

>>>

# +和*

>>>(1, 2, 3) + (5, 2, 0) + (9, 9, 6)

(1, 2, 3, 5, 2, 0, 9, 9, 6)

>>>(5, 2, 0)*4

(5, 2, 0, 5, 2, 0, 5, 2, 0, 5, 2, 0)

>>>

(3)拆分元组:

>>>tup = (5, 2, 0)

>>>a, b, c = tup

>>>b

2

>>>a

5

>>>tup = 9, 4, (5, 2, 0)

>>>a, b, (c, d, e) = tup

>>>c, d, e

(5, 2, 0)

>>>a,b

(9, 4)

# 变量赋值

>>>a, b =1, 2

>>>a

1

>>>b

2

# 变量替换

>>>a,b =b, a

>>>a, b

(4, 9)

# 摘取部分元素

>>>a, b, *rest = tup

>>>rest

[(5, 2, 0)]

2、列表

(1)创建访问列表

>>> a_list = [1, 2, 3, 4]

>>> a_list

[1, 2, 3, 4]

# list 函数常用来在数据处理中实体化迭代器或生成器:

>>> tup = (5, 2, 0)

>>> b_list = list(tup)

>>> b_list

[5, 2, 0]

>>> b_list[0]

5

>>> ran = range(10)

>>> ran

range(0, 10)

>>> list(ran)

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> tuple(ran)

(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)

(2)插入删除元素(append, insert, pop, remove),(in, not in)

1)append 尾部追加

>>> c_list = ['fool', 'tool', 'zoo' ,'so']

>>> c_list.append('what')

>>> c_list

['fool', 'tool', 'zoo', 'so', 'what']

2)insert 指定位置插入(0 -最后一个位置)

>>> c_list.insert(0,'I')

>>> c_list

['I', 'fool', 'tool', 'zoo', 'so', 'what']

3)pop insert的逆运算

>>> c_list.pop(2)

'tool'

>>> c_list

['I', 'fool', 'zoo', 'so', 'what']

4)remove 删除第一个指定元素

>>> c_list.remove('zoo')

>>> c_list

['I', 'fool', 'so', 'what']

>>> 'you' not in c_list

True

5)IN 和NOT IN

>>> I in c_list

Traceback (most recent call last):

File "", line 1, in

I in c_list

NameError: name 'I' is not defined

>>> 'I' in  c_list

True

(3)串联,组合, 排序(+, extend, sort)

(4)切片:

seq[start:stop[:step]]

切片的起始元素是包括的,不包含结束元素。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值