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 "<pyshell#10>", line 1, in <module>
    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 "<pyshell#12>", line 1, in <module>
    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 "<pyshell#15>", line 1, in <module>
    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、列表(list)

(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 "<pyshell#23>", line 1, in <module>
    I in c_list
NameError: name 'I' is not defined
>>> 'I' in  c_list
True

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

  (4)切片:

   seq[start:stop[:step]]

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

3、字典:

(1)创建、访问、键是否存在;用序列创建字典

>>> empty_dict = {}
>>> d1 = {'a' : 'some value', 'b' : [1, 2, 3, 4]}
>>> d1
{'a': 'some value', 'b': [1, 2, 3, 4]}

>>> d1['b']
[1, 2, 3, 4]

>>> 'b' in d1
True

(2)del关键字或pop方法

>>> d1[5] = 'some value'
>>> d1
{'a': 'some value', 'b': [1, 2, 3, 4], 7: 'an integer', 5: 'some value'}
>>> d1['dummy'] = 'another value'
>>> d1
{'a': 'some value', 'b': [1, 2, 3, 4], 7: 'an integer', 5: 'some value', 'dummy': 'another value'}


>>> del d1[5]
>>> d1
{'a': 'some value', 'b': [1, 2, 3, 4], 7: 'an integer', 'dummy': 'another value'}


>>> ret = d1.pop('dummy')
>>> ret
'another value'
>>> d1
{'a': 'some value', 'b': [1, 2, 3, 4], 7: 'an integer'}

(3)keys和values是字典的键和值的迭代器方法

>>> list(d1.keys())
['a', 'b', 7]


>>> list(d1.values())
['some value', [1, 2, 3, 4], 'an integer']


>>> d1.values();
dict_values(['some value', [1, 2, 3, 4], 'an integer'])

(4)用update方法可以将一个字典与另一个融合:

>>> d1.update({'b': 'foo', 'c': 12})
>>> d1
{'a': 'some value', 'b': 'foo', 7: 'an integer', 'c': 12}

(5)默认值;有效键类型

4、集合(set):

set([2, 2, 2, 1, 3, 3])

5、序列函数:

(1)enumerate();

enumerate(sequence, [start=0])

# sequence 表示一个序列、迭代器或者支持迭代的对象
# start = 0 表示 下标从0开始
# 返回 enumerate(枚举) 对象。

seq = ['one', 'two', 'three']
for i, element in enumerate(seq):
    print(i, element)


# 结果:
0 one
1 two
2 three

(2)sorted();

(3)zip()

### zip()
## 参数是若干个可迭代对象。


## 1、举例
a = [1, 2, 3]
b = ['one', 'two', 'three']
c = ['apple', 'banana', 'orange', 'egg']

# 将若干个可迭代对象的对应元素打包成一个一个元组
# 然后返回由这些元组组成的对象
zip_1 = zip(a, b)
zip_2 = zip(a, c)

print(zip_1)
print(zip_2)


## 2、 list() 可将其转换为列表
print(list(zip_1))
print(list(zip_2)) # 元素个数以最短的列表一致


## 3、zip(*) 是 zip() 的逆操作
a1, b1 = zip(*zip(a, b))
print(list(a1))
print(list(b1))
### 结果

## 1
<zip object at 0x0000026655A6E4C0>
<zip object at 0x0000026655A619C0>

## 2
[(1, 'one'), (2, 'two'), (3, 'three')]
[(1, 'apple'), (2, 'banana'), (3, 'orange')]

## 3
[1, 2, 3]
['one', 'two', 'three']

(4)reversed()# 生成器,只有实体化(即列表或for循环)之后才能创建翻转的序列。

6、列表、集合、字典的推导式

[expr for val in collection if condition]

1、列表推导式

[x*y for x in range(1,5) if x > 2 for y in range(1,4) if y < 3]

# 等价于

for x in range(1,5)
    if x > 2
        for y in range(1,4)
            if y < 3
                x*y

参考:Python 列表推导式

7、嵌套列表推导式

mat = [[1,2,3], [4,5,6], [7,8,9]]
new_mat = [ [row[i] for row in mat] for i in [0,1,2] ] # 嵌套
print(new_mat)


# 运行结果:
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]

参考:Python3基础(六) 深入list列表 | 神奕的博客

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值