Python组合数据类型——序列类型:列表、元组

2年前 (2022) 程序员胖胖胖虎阿
220 0 0

​​#21天学习挑战赛—100天精通Python从入门到就业#
Python组合数据类型——序列类型:列表、元组

🤵‍♂️ 个人主页: @Flyme awei 个主页
👨‍💻 作者简介:Python领域新星创作者。
📒 系列专栏:《在线编程-Python篇》
🌐推荐一款找工作神器网站:《牛客网》|笔试题库|面试经验|
🐋 希望大家多多支持😘一起进步呀!
📝 如果文章对你有帮助的话,欢迎评论 💬点赞 👍收藏 📂加关注

前言

  今天是《CSDN21天学习挑战赛》的第8天
  昨天学习了【Python语言程序的流程控制结构】顺序、分支、循环结构。
  今天将学习Python组合数据类型——序列类型:列表、元组。

活动地址:CSDN21天学习挑战赛

文章目录

  • 前言
  • Python序列类型--列表、元组
  • 一、列表类型
    • 1.列表的定义
    • 2.列表的特点
    • 3.列表的索引
    • 4.列表的切片
  • 二、列表类型的操作
    • 1.列表操作函数
    • 2.列表操作方法
      • 2.1列表元素的增加操作
      • 2.2列表元素的删除操作
      • 2.3列表元素的修改操作
      • 2.4列表元素的排序操作
    • 3.列表生成式
  • 三、元组类型
    • 1.什么是元组
    • 2.元组的创建方式
    • 3.元组的遍历
  • 四、总结

Python序列类型–列表、元组

一、列表类型

1.列表的定义

列表类型是包含0个或多个元素的有序序列,属于序列类型。列表可以进行元素的增加、删除、替换、查找等操作。列表没有长度限制,无素类型可以不同,不需要预定长度。

列表类型用中括号[]表示,也可以通过list(x)函数将集合或字符串类型转换成列表类型。list()函数可生成空列表。

列表需要使用中括号[],元素之间使用英文的逗号进行分隔

列表示意图:
Python组合数据类型——序列类型:列表、元组
列表创建方式

  1. 使用[]方括号
lst = ['hello', 'world', 'java']
print(lst)
  1. 使用内置函数list()
lst2 = list(['hello', 'world', 'java'] + ['hello', 'world', 'java'])
print(lst2)
  1. 列表生成式
lst = [i for i in range(1, 11)]
print(lst)

2.列表的特点

  1. 列表元素按顺序有序排列
  2. 索引映射唯一一个数据
  3. 列表可以存储重复数据
  4. 任意数据类型混存
  5. 根据需要动态分配内存空间

3.列表的索引

索引是列表的基本操作,用于获得列表第一个元素。该操作沿用序列类型的索引方式,即正向递增序号和反向递减序号,使用中括号作为索引操作符,索引序号不能超过列表的元素范围,否则会产生IndexErrorr的错误。

获取列表中指定元素索引

语法:列表或列表变量.index('要获取索引的元素',起始位置,结束位置)

如果列表中含有相同元素,只返回相同元素的第一个元素的索引。

# 如果列表中含有相同元素,只返回相同元素的第一个元素的索引

lst = ['hello', 'world', 'java', 'hello', 'world', 'java']
print(lst.index('java'))  # 2
print(lst.index('java', 3, 6))  # 5

可以使用遍历循环对列表类型的元素进行遍历操作。

语法:for 迭代变量 in 列表名:

# 列表元素的遍历

lst = [10, 20, 30, 40, 50, 60, 70, 80]
for i in lst:
    print(i)

output:
10
20
30
40
50
60
70
80

4.列表的切片

切片是列表的基本操作,用于获得列表的一个片段,即获得零个或多个元素。切片后的结果也是列表类型。
切片有两种使用方式:

  • 列表或列表变量[N:M]
  • 列表或列表变量[N:M:K]

根据索引获取元素值

lst = ['hello', 'world', 'java', 'hello', 'world', 'java']

'''获取单个元素'''
# 获取列表索引为 2的元素
print(lst[2])  # java

# 获取列表索引为-3的元素
print(lst[-3])  # hello

'''获取多个元素   返回值为一个列表'''
# lst = [start(默认0开始) : stop(默认最后) : step(默认步长1)]
# step 为负数时相反

print(lst[0:5:1])
# ['hello', 'world', 'java', 'hello', 'world']

二、列表类型的操作

1.列表操作函数

操作函数 描述
len(ls) 列表ls的元素个数(长度)
min(ls) 列表ls的最小元素
max(ls) 列表ls的最大元素
list(x) x转换为列表类型
# -*- coding: utf-8 -*-
# @File  : 列表操作函数.py
# @author: Flyme awei 
# @email : 1071505897@qq.com
# @Time  : 2022/8/8 0:15

ls = [1, 3, 5, 7, 9]
print(len(ls))
print(max(ls))
print(min(ls))
x = (1, 3, 5, 7, 9)
print(list(x))

Python组合数据类型——序列类型:列表、元组

2.列表操作方法

list类源码:

class list(object):
    """
    Built-in mutable sequence.
    
    If no argument is given, the constructor creates a new empty list.
    The argument must be an iterable if specified.
    """
    def append(self, *args, **kwargs): # real signature unknown
        """ Append object to the end of the list. """
        pass

    def clear(self, *args, **kwargs): # real signature unknown
        """ Remove all items from list. """
        pass

    def copy(self, *args, **kwargs): # real signature unknown
        """ Return a shallow copy of the list. """
        pass

    def count(self, *args, **kwargs): # real signature unknown
        """ Return number of occurrences of value. """
        pass

    def extend(self, *args, **kwargs): # real signature unknown
        """ Extend list by appending elements from the iterable. """
        pass

    def index(self, *args, **kwargs): # real signature unknown
        """
        Return first index of value.
        
        Raises ValueError if the value is not present.
        """
        pass

    def insert(self, *args, **kwargs): # real signature unknown
        """ Insert object before index. """
        pass

    def pop(self, *args, **kwargs): # real signature unknown
        """
        Remove and return item at index (default last).
        
        Raises IndexError if list is empty or index is out of range.
        """
        pass

    def remove(self, *args, **kwargs): # real signature unknown
        """
        Remove first occurrence of value.
        
        Raises ValueError if the value is not present.
        """
        pass

    def reverse(self, *args, **kwargs): # real signature unknown
        """ Reverse *IN PLACE*. """
        pass

    def sort(self, *args, **kwargs): # real signature unknown
        """
        Sort the list in ascending order and return None.
        
        The sort is in-place (i.e. the list itself is modified) and stable (i.e. the
        order of two equal elements is maintained).
        
        If a key function is given, apply it once to each list item and sort them,
        ascending or descending, according to their function values.
        
        The reverse flag can be set to sort in descending order.
        """
        pass

    def __add__(self, *args, **kwargs): # real signature unknown
        """ Return self+value. """
        pass

    def __contains__(self, *args, **kwargs): # real signature unknown
        """ Return key in self. """
        pass

    def __delitem__(self, *args, **kwargs): # real signature unknown
        """ Delete self[key]. """
        pass

    def __eq__(self, *args, **kwargs): # real signature unknown
        """ Return self==value. """
        pass

    def __getattribute__(self, *args, **kwargs): # real signature unknown
        """ Return getattr(self, name). """
        pass

    def __getitem__(self, y): # real signature unknown; restored from __doc__
        """ x.__getitem__(y) <==> x[y] """
        pass

    def __ge__(self, *args, **kwargs): # real signature unknown
        """ Return self>=value. """
        pass

    def __gt__(self, *args, **kwargs): # real signature unknown
        """ Return self>value. """
        pass

    def __iadd__(self, *args, **kwargs): # real signature unknown
        """ Implement self+=value. """
        pass

    def __imul__(self, *args, **kwargs): # real signature unknown
        """ Implement self*=value. """
        pass

    def __init__(self, seq=()): # known special case of list.__init__
        """
        Built-in mutable sequence.
        
        If no argument is given, the constructor creates a new empty list.
        The argument must be an iterable if specified.
        # (copied from class doc)
        """
        pass

    def __iter__(self, *args, **kwargs): # real signature unknown
        """ Implement iter(self). """
        pass

    def __len__(self, *args, **kwargs): # real signature unknown
        """ Return len(self). """
        pass

    def __le__(self, *args, **kwargs): # real signature unknown
        """ Return self<=value. """
        pass

    def __lt__(self, *args, **kwargs): # real signature unknown
        """ Return self<value. """
        pass

    def __mul__(self, *args, **kwargs): # real signature unknown
        """ Return self*value. """
        pass

    @staticmethod # known case of __new__
    def __new__(*args, **kwargs): # real signature unknown
        """ Create and return a new object.  See help(type) for accurate signature. """
        pass

    def __ne__(self, *args, **kwargs): # real signature unknown
        """ Return self!=value. """
        pass

    def __repr__(self, *args, **kwargs): # real signature unknown
        """ Return repr(self). """
        pass

    def __reversed__(self, *args, **kwargs): # real signature unknown
        """ Return a reverse iterator over the list. """
        pass

    def __rmul__(self, *args, **kwargs): # real signature unknown
        """ Return value*self. """
        pass

    def __setitem__(self, *args, **kwargs): # real signature unknown
        """ Set self[key] to value. """
        pass

    def __sizeof__(self, *args, **kwargs): # real signature unknown
        """ Return the size of the list in memory, in bytes. """
        pass

    __hash__ = None
    

列表类型的一些常用操作方法:

方法 描述
ls.append(x) 在列表ls末尾添加一个元素x
ls.insert(i, x) 在列表ls的第i个位置增加元素x
ls.clear() 删除列表ls所有元素
ls.pop(i) 将列表ls的第i个元素取出并从ls中删除该元素
ls.remove(x) 将列表中出现的第一个元素x删除
ls.reverse() 将列表ls中的元素反转
ls.copy() 生成一个新列表,复制ls中的所有元素

2.1列表元素的增加操作

方法 描述
ls.append(x) 在列表ls末尾添加一个元素x
ls.insert(i, x) 在列表ls的第i个位置增加元素x
ls.extend() 在列表ls末尾至少添加一个元素
切片 在列表任意位置至少添加一个元素
lst = [10, 20, 30]
lst1 = ['hello', 'world']
print(lst)
print("添加元素之前id:", id(lst))

# 1. append(要添加的元素)  在列表末尾添加一个元素
lst.append(100)
print(lst)
print("添加元素之后id:", id(lst))

# 2. extend() 在列表末尾至少添加一个元素
lst.extend(lst1)
print(lst)

# 3. insert(索引, 要添加的对象)在任意(指定索引)位置添加一个元素
lst.insert(4, 'python')
print(lst)

# 4.切片 在任意位置添加至少一个元素
# lst[要切的位置索引 : 结束位置 : 步长默认为以1]=要添加的列表
lst[1:5:3] = lst1
print(lst)

Python组合数据类型——序列类型:列表、元组

2.2列表元素的删除操作

方法 描述
ls.remove(x) 将列表中出现的第一个元素x删除
pop() 删除一个指定索引位置上的元素
切片 一次至少删除一个元素
clear() 清空列表
del 删除列表

代码:

lst = [10, 20, 30, 20, 40, 50, 60, 70, 80, 90]
# 1. remove(要移除的元素)  从列表中移除一个元素,重复只删一个,元素不存抛异常
lst.remove(20)
print(lst)

# 2. pop(索引)  删除一个指定索引上的元素,不指定索引删除最后一个元素,指定索引不存在抛异常
lst.pop(7)
print(lst)
lst.pop()
print(lst)

# 3. 切片操作 删除至少一个元素,将产生一个新的列表对象
new_lst = lst[1:4]  # 索引 1,2,3,产生一个新列表
print(new_lst)
'''不产生新的列表对象,而是删除原列表中的内容'''
lst[1:6] = []
print(lst)

# 4. clear 清空列表
lst.clear()
print(lst)

# 5. del  删除列表
del lst
# print(lst)

运行结果:
Python组合数据类型——序列类型:列表、元组

2.3列表元素的修改操作

# 为指定索引的元素赋予一个新值
lst = [10, 20, 30, 40]
lst[2] = 100
print(lst)

# 为指定的切片赋予一个新值
lst[1:2] = [100, 200, 300]
print(lst)

Python组合数据类型——序列类型:列表、元组

2.4列表元素的排序操作

sort()方法

class list(object):
    def sort(self, *args, **kwargs): # real signature unknown
        """
        Sort the list in ascending order and return None.
        
        The sort is in-place (i.e. the list itself is modified) and stable (i.e. the
        order of two equal elements is maintained).
        
        If a key function is given, apply it once to each list item and sort them,
        ascending or descending, according to their function values.
        
        The reverse flag can be set to sort in descending order.
        """
        pass

按升序对列表进行排序,返回None
排序是原地的(即列表本身被修改)和稳定的(即
保持两个相等元素的顺序)。
如果给出了一个键函数,对每个列表项应用一次,并对它们进行排序,
根据它们的函数值升序或降序。
反向标志可以设置为降序排序。

内置函数sorted()

def sorted(*args, **kwargs): # real signature unknown
    """
    Return a new list containing all items from the iterable in ascending order.
    
    A custom key function can be supplied to customize the sort order, and the
    reverse flag can be set to request the result in descending order.
    """
    pass

返回一个新列表,其中包含可迭代对象中的所有项,按升序排列。
可以提供自定义键函数来自定义排序顺序
可以设置reverse标志,以降序请求结果。

# 1.调用 sort()方法,sort()方法默认是 升序 排序,在调用该方法后,列表中的元素会按照从小到大的顺序排列
lst = [23, 46, 67, 12, 8, 27]
lst.sort()
print(lst)

# 2.如果我们想让其降序 排序,则可以通过指定关键字参数reverse
lst = [20, 40, 10, 98, 54]
print('排序前的列表', lst)
lst.sort(reverse=True)
print('排序后的列表', lst)

# 升序
lst.sort(reverse=False)
print('排序后的列表', lst)

# 使用内置函数 sorted() 对列表进行排序,将产生一个新的对象
lst = [20, 40, 10, 98, 54]
print(sorted(lst))  # 未指定升序
print(sorted(lst, reverse=True))  # 指定降序

Python组合数据类型——序列类型:列表、元组

3.列表生成式

列表生成式: 简称列表生成的公式。

语法格式:
lst = [列表元素表达式 for 自定义变量 in 可迭代对象]
例:lst = [i for i in range(1, 11)]

lst = [i for i in range(1, 11)]
print(lst)

Python组合数据类型——序列类型:列表、元组

三、元组类型

1.什么是元组

元组:Python内置的数据结构之一,是一个不可变序列。

不可变序列与可变序列

  • 不变可变序:字符串元组
    不变可变序列:没有增、删,改的操作
# 修改后对象地址会发生改变
s = 'hello'
print(id(s))  # 2533879685808
s = s + 'world'
print(id(s))  # 2533879671984
print(s)  # helloworld
  • 可变序列:列表字典
    可变序列:可以对序列执行增、删、改操作,对象地址不发生更改
# 可变序列:可以执行增删改操作,对象地址不发生改变
lst = [10, 20, 40]
print(id(lst))
lst.append(50)
print(id(lst))

Python组合数据类型——序列类型:列表、元组

2.元组的创建方式

  1. 直接小括号()
# 1.使用()
t = ('python', 'java')
print(t)  # ('python', 'java')
print(type(t))  # <class 'tuple'>
  1. 使用内置函数tuple()
# 2.使用内置函数tuple()
t2 = tuple(('java', 'python'))
print(t2)  # ('java', 'python')
print(type(t2))  # <class 'tuple'>
  1. 只包含一个元组的元素需要使用逗号,和小括号()
# 3.只包含一个元素,需要使用逗号和小括号(只有一个元素的时候必须加上,)
t3 = ('hello', )
print(t3)  # ('hello',)
print(type(t3))  # <class 'tuple'>
  1. 空元组创建方式
# 空元组创建方式
t4 = ()
t5 = tuple()
print('空元组', t4, t5)  # 空元组 () ()
print('空列表', [], list())  # 空列表 [] []
print('空字典', {}, dict())  # 空字典 {} {}
# print('空集合', {}, set())

为什么要将元组设计成不可变序列

在多任务环境下,同时操作对象时不需要加锁,因此,在程序中尽量使用不可变序列 。
注意事项:元组中存储的是对象的引用

  • 如果元组中对象本身不可对象,则不能再引用其它对象。
  • 如果元组中的对象是可变对象,则可变对象的引用不允许改变,但数据可以改变。

这样设计的原因是,元组的不可变性保证了数据的完整性,这样如果有多个地方都用到了元组,我们可以保证它的数据不会被改变。并且,相较于列表,元组的读取速度更快,占用的内存空间更小,并且可以作为字典的key去使用。

# 这样设计的原因是,元组的不可变性保证了数据的完整性,这样如果有多个地方都用到了元组,我们可以保证它的数据不会被改变。
# 并且,相较于列表,元组的读取速度更快,占用的内存空间更小,并且可以作为字典的key去使用。

t = (10, [20, 30], 40)
print(t)  # (10, [20, 30], 40)
print(type(t), id(t))  # <class 'tuple'> 2972759079744
print(t[0], type(t[0]), id(t[0]))  # 10 <class 'int'> 140726042761152
print(t[1], type(t[1]), id(t[1]))  # [20, 30] <class 'list'> 2972768483776
print(t[2], type(t[2]), id(t[2]))  # 40 <class 'int'> 140726042762112
t[1].append(100)
print(t, id(t))  # (10, [20, 30, 100], 40) 2972759079744

3.元组的遍历

元组是可迭代对象,所以可以使用for...in进行遍历

# 元组遍历
t = ('hello', 'java', 90)
print(t[0])
print(t[1])
print(t[2])

for item in t:
    print(item, end=' ')

Python组合数据类型——序列类型:列表、元组
列表类型覆盖了元组类型的所有主要功能。

四、总结

列表类型的一些常用操作方法:

方法 描述
ls.append(x) 在列表ls末尾添加一个元素x
ls.insert(i, x) 在列表ls的第i个位置增加元素x
ls.clear() 删除列表ls所有元素
ls.pop(i) 将列表ls的第i个元素取出并从ls中删除该元素
ls.remove(x) 将列表中出现的第一个元素x删除
ls.reverse() 将列表ls中的元素反转
ls.copy() 生成一个新列表,复制ls中的所有元素

相关文章

暂无评论

暂无评论...