第6章 python列表和元组

1、列表的介绍

1、列表的创建和赋值
a = [None, True, 1, "abc", (1,), {"1": "1"}, 7 - 9j, ]
b = list("abc")
print(a, b, sep="\n")


[None, True, 1, 'abc', (1,), {'1': '1'}, (7-9j)]
['a', 'b', 'c']
2、访问列表的元素

通过下标索引  []  和切片   [:]

a = [None, True, 1, "abc", (1,), {"1": "1"}, 7 - 9j, ]
b = list("abc")
print(a[1], b[:2], sep="\n")


E:\env\python39\python.exe D:\项目\python\deke\test2.py 
True
['a', 'b']
3、更新列表的值

你可以通过在等号的左边指定一个索引或者索引范围的方式来更新一个或几个元素,你也 可以用 append()方法来追加元素到列表中去.

a = [None, True, 1, "abc", (1,), {"1": "1"}, 7 - 9j, ]
b = list("abc")
a[1] = 1
b.append("123")
print(a[1], b[:2], sep="\n")


[None, 1, 1, 'abc', (1,), {'1': '1'}, (7-9j)]
['a', 'b', 'c', '123']
4、删除列表元素和本身

要删除列表中的元素,如果你确切的知道要删除元素的素引可以用 del 语句,否则可以用 remove()方法.

a = [1, 2]
b = [None, 1, None]
c = list("123456")
del a[0]
b.remove(None)
d = c.pop(2)
print(a, b, c, d, sep="\n")



[2]
[1, None]
['1', '2', '4', '5', '6']
3


你还可以通过 pop()方法来删除并从列表中返回一个特定对象。

删除列表本身可以使用del语句删除列表对象。

2、列表的操作符

1、标准类型操作符
a = ["b", 2]
b = ["a", 1, "b"]
print(a > b, a < b, a == b, sep="\n")
print(ord("a"), ord("b"), end="字符串按照ascii码比较")


True
False
False
97 98字符串按照ascii码比较
2、序列类型操作符
1、切片[],[:]
alist[0]
alist[1:20]
alist[:10]
alist[-2:]
2、成员操作符 in、 not in

列表中(同样适用于元组),我们可以检查一个对象是否是一个列表(或者元组)的成员.

3、链接操作符 +
a = ["b", 2]
b = ["a", 1, "b"]
c = a + b
print(a, b, c, sep="----")
print(id(a), id(b), id(c), sep="----")



['b', 2]----['a', 1, 'b']----['b', 2, 'a', 1, 'b']
2057300550784----2057300864384----2057303483328

从结果上看,列表的+链接操作符得到的结果是  重新定义了一个列表进行存储

4、重复操作符 *

重复操作符可能更多的应用在字符串类型中,不过,列表和元组跟字符串同属序列类型,所 以需要的时候也可以使用这一操作。

a = ["b", 2]
c = a * 5
print(a, c, sep="\n")
print(id(a), id(c), sep="---")


['b', 2]
['b', 2, 'b', 2, 'b', 2, 'b', 2, 'b', 2]
1916310922432---1916311235712

从结果上看,列表的*链接操作符得到的结果是  重新定义了一个列表进行存储

3、列表类型操作符和列表解析

其实 Python 中没有专门用于列表类型的操作符.列表可以使用大部分的对象和序列类型的 操作符.此外,列表类型有属于自己的方法.列表才有的构建--列表解析。

>>> [ i * 2 for i in [8, -2, 5] ]
[16, -4, 10]
>>> [ i for i in range(8) if i % 2 == 0 ]
[0, 2, 4, 6] 

3、列表的内建函数

1、标准类型内建函数

cmp()、 str()、 cmp()、type()  函数

2、序列类型内建函数

len() 、max() 、min()、sorted()、reversed()、sum()、list()、tuple()

enumerate()、 zip()

a = list("abcdefg")
for i, album in enumerate(a):
    print(i, album)


0 a
1 b
2 c
3 d
4 e
5 f
6 g
a = list("abcdefg")
b = list("123456")
print(list(zip(b, a)))

[('1', 'a'), ('2', 'b'), ('3', 'c'), ('4', 'd'), ('5', 'e'), ('6', 'f')]
3、列表类型内建函数
['__add__', '__class__', '__class_getitem__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__',
     '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__',
     '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__',
     '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__',
     '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove',
     'reverse', 'sort']
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
        """ 向列表结尾添加元素 """
        pass

    def clear(self, *args, **kwargs):  # real signature unknown
        """ 清空列表元素 """
        pass

    def copy(self, *args, **kwargs):  # real signature unknown
        """ 浅拷贝 """
        pass

    def count(self, *args, **kwargs):  # real signature unknown
        """返回元素在列表的次数"""
        pass

    def extend(self, *args, **kwargs):  # real signature unknown
        """ 通过添加可迭代项中的元素来扩展列表。"""
        pass

    def index(self, obj, i=0, j=len(list)):  # real signature unknown
        """
        返回第一个出现元素的下标

        如果没有该元素则抛出异常.
        """
        pass

    def insert(self, index, obj):  # real signature unknown
        """ 在某下标元素之前插入 """
        pass

    def pop(self, index=-1):  # real signature unknown
        """
        返回删除指定下标的元素

        如果下标超出索引范围,抛出异常.
        """
        pass

    def remove(self, *args, **kwargs):  # real signature unknown
        """
        删除第一个出现的元素

        如果元素不存在抛出异常
        """
        pass

    def reverse(self, *args, **kwargs):  # real signature unknown
        """ 列表的反转. """
        pass

    def sort(self, (func=None, key=None, reverse=False):  # real signature unknown
        """
        
        
        利用可选的比较函数 func 排序列表成员;当提取要排序的元素时 key 是一个回调,并且如果
        reverse 标记为 True,则 list 将以倒序排序

        """

        pass

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

    def __class_getitem__(self, *args, **kwargs):  # real signature unknown
        """ See PEP 585 """
        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

4、列表的特殊性

由于列表数据结构的特殊性,可用列表构建堆栈、队列数据结构

5、元组的介绍

1、元组的创建和赋值

注意单元素元组的创建必须加上逗号。

a = (1,)
b = (1, 2, 3, 4, 5, 6)
c = tuple("abcdef")
a = (1,)
b = (1)
print(a, b, sep="\n")


(1,)
1
# a表示单元素元组,b的括号是代表优先数据的计算
2、元组元素的访问

同列表。

3、元组的更新

元组是不可变类型,第一层元素不能修改。其实元组也不是那么不可变,除了第一层元素无法修改,其他层级是可以修改的,以及切片操作[:]、链接+、重复*。下面在元组的特殊行会讲到。

4、元组元素的删除以及本身的删除

元组元素的删除同元素更新一样,删除元组本身可用del语句。

6、元组操作符和内建函数

1、标准操作符

同列表

2、序列操作符

同列表

a = (1,) * 10
b = a + (1, 2)
c = a[:2]
print(a, b, c, sep="\n")



(1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2)
(1, 1)
3、元组的内建函数
1、标准类型内建函数

同列表

2、序列类型内建函数

同列表

3、元组的内建函数
class tuple(object):
    """
    Built-in immutable sequence.

    If no argument is given, the constructor returns an empty tuple.
    If iterable is specified the tuple is initialized from iterable's items.

    If the argument is a tuple, the return value is the same object.
    """

    def count(self, *args, **kwargs):  # real signature unknown
        """返回出现该元素的数量"""
        pass

    def index(self, *args, **kwargs):  # real signature unknown
        """
        返回第一个出现该元素下标的.

        如果不存在抛出异常
        """
        pass

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

    def __class_getitem__(self, *args, **kwargs):  # real signature unknown
        """ See PEP 585 """
        pass

    def __contains__(self, *args, **kwargs):  # real signature unknown
        """ Return key in self. """
        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, *args, **kwargs):  # real signature unknown
        """ Return self[key]. """
        pass

    def __getnewargs__(self, *args, **kwargs):  # real signature unknown
        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 __hash__(self, *args, **kwargs):  # real signature unknown
        """ Return hash(self). """
        pass

    def __init__(self, seq=()):  # known special case of tuple.__init__
        """
        Built-in immutable sequence.

        If no argument is given, the constructor returns an empty tuple.
        If iterable is specified the tuple is initialized from iterable's items.

        If the argument is a tuple, the return value is the same object.
        # (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 __rmul__(self, *args, **kwargs):  # real signature unknown
        """ Return value*self. """
        pass

7、元组的特殊性

1、元组的不可变性

2、元组也不是那么不可变,序列操作符中的切片、链接+,重复*,等都可以改变元组。

3、默认集合类型:所有的多对象的,逗号分隔的,没有明确用符号定义的,比如说像用方括号表示列表和用 圆括号表示元组一样,等等这些集合默认的类型都是元组,a = 1,2  

a = 1, 2
print(a)

4、单元素元组:必须加上逗号

5、字典的关键字:可以作为字典的键,这也是取决于元组的不可变性。

8、深拷贝、浅拷贝以及引用

9、列表vs元组

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值