python学习——练习题(7)

时间:2023-02-22 14:35:04
"""
题目:将一个列表的数据复制到另一个列表中。
"""
import copy


def validate(a, b):
    """
    验证复制结果
    :param a:
    :param b:
    :return:
    """
    print("a =", a)
    print("b =", b)
    print("a == b is", a == b)
    print("id(a) =", id(a))
    print("id(b) =", id(b))
    a[0][0] = 0
    print("a[0][0] = 0后,a =", a)
    print("a[0][0] = 0后,b =", b)
    a[0] = 1
    print("a[0] = 1后,a =", a)
    print("a[0] = 1后,b =", b)


def answer1():
    """
    直接将列表a=列表b,那么a和b是完全相同的,a列表发生改变时,b列表会跟着改变
    :return:
    """
    print("输出一:")
    a = [[1, 2], [3, 4]]
    b = a
    validate(a, b)


answer1()


def answer2():
    """
    手动复制一层
    :return:
    """
    print("\n输出二:")
    a = [[1, 2], [3, 4]]
    b = []
    for i in a:
        b.append(i)
    validate(a, b)


answer2()


def answer3():
    """
    利用列表自带的copy方法,但是也只能copy一层
    :return:
    """
    print("\n输出三:")
    a = [[1, 2], [3, 4]]
    b = a.copy()
    validate(a, b)


answer3()


def answer4():
    """
    利用列表的切片
    :return:
    """
    print("\n输出四:")
    a = [[1, 2], [3, 4]]
    b = a[:]
    validate(a, b)


answer4()


def answer5():
    """
    深拷贝copy.deepcopy
    :return:
    """
    print("\n输出五:")
    a = [[1, 2], [3, 4]]
    b = copy.deepcopy(a)
    validate(a, b)


answer5()


def answer6():
    """
    浅拷贝copy.copy,同answer3
    :return:
    """
    print("\n输出六:")
    a = [[1, 2], [3, 4]]
    b = copy.copy(a)
    validate(a, b)


answer6()


def answer7():
    """
    使用列表生成式
    利用列表的for处理,好像是生成器
    :return:
    """
    print("\n输出七:")
    a = [[1, 2], [3, 4]]
    b = [i for i in a]
    validate(a, b)


answer7()


def answer8():
    """
    利用列表乘以1来生成
    序列相加  相乘:
    [1,2,3]+[4,5,6]=[1,2,3,4,5,6]  学列相加就是连接在一起
    [1,2,3]*3=[1,2,3,1,2,3,1,2,3]   序列乘以一个常数N就是将序列复制N次
    [1,2,3]*[1,2,3]=[]  报错TypeError
    :return:
    """
    print("\n输出八:")
    a = [[1, 2], [3, 4]]
    b = a * 1
    validate(a, b)


answer8()


def answer9():
    """
    表1拓展到表2中
    :return:
    """
    print("\n输出九:")
    a = [[1, 2], [3, 4]]
    b = []
    b.extend(a)
    validate(a, b)


answer9()