数据团Python_3. Python序列及整体概述及通用操作

2017-03-20  本文已影响24人  00e6a8fd618f

3. Python序列及整体概述及通用操作


序列是Python最基本的数据结构。

Python数据存储方式为动态类型,元素赋值只是建立对应的“连接”。


3.1 Python可变序列:列表list

列表list[]

  1. 包含任意类型的对象
    • 数值
    • 字符串
    • 列表
  2. 通过下标访问序列中的值,顺序不可变
    • m[0]第一个元素,m[-1]最后一个元素
  3. 可随意变换序列长度
    • m.append()增加元素
    • m.removed()移除现有元素
    • ()中为元素值
  4. 可嵌套
  5. 可原位改变

3.2 Python不可变序列:元祖tuple

元祖tuple()

  1. 可包含任意类型对象
  2. 通过下标索引访问序列中值
  3. 可嵌套
  4. 申明元祖可以不加()

3.3 Python生成器:范围range

range()生成器,指向一个范围。

range()生成整数。


3.4 Python不可变序列:文本序列str

文本实为序列。

>>> name = 'fengxuan'
>>> name
'fengxuan'
>>> type(name)
<class 'str'>
>>> list(name)
['f', 'e', 'n', 'g', 'x', 'u', 'a', 'n']
>>> name2 = "Tom"
>>> name2[0] = "A"
Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    name2[0] = "A"
TypeError: 'str' object does not support item assignment
>>> name.replace("f", "F")
'Fengxuan'
>>> name
'fengxuan'
>>> name = name.replace("f", "F")
>>> name
'Fengxuan'

3.5 可变序列/不可变序列通用操作

  1. 判断值是否属于序列
    • in
    • not in
  2. 序列连续与重复
  3. 下标索引及切片
    • x[1] x[2]
    • x[:] x[:5] x[2:5] x[3:] x[: -1]
    • 按照步长访问x[ : :步长]

基本的内置全局函数:

  1. x=list(range(10))
  2. len(x)=10
  3. max(x)=9
  4. min(x)=0
  5. sum(x)=45
  6. x_index("4")确定元素下标
  7. x.count("7")计算出现次数

上一篇 下一篇

猜你喜欢

热点阅读