zoukankan      html  css  js  c++  java
  • 列表的拷贝

    将一个列表的值复制到另一个列表,如将my_foods拷贝到friend_foods,需要使用如下的程序,才可分别对这两个列表的值进行修改,两个列表的值可以不同

    my_foods = ['pizza', 'falafel', 'carrot cake']
    friend_foods = my_foods[:]   #也可使用   friend_foods = my_foods.copy()
    my_foods.append('cannoli')
    friend_foods.append('ice cream')
    print("My favorite foods are:")
    print(my_foods)
    print(" My friend's favorite foods are:")
    print(friend_foods)
    输出
    My favorite foods are:
    ['pizza', 'falafel', 'carrot cake', 'cannoli']
    My friend's favorite foods are:
    ['pizza', 'falafel', 'carrot cake', 'ice cream']
     
     
    如果使用
    friend_foods = my_foods
    my_foods.append('cannoli')
    friend_foods.append('ice cream')
    print("My favorite foods are:")
    print(my_foods)
    print(" My friend's favorite foods are:")
    print(friend_foods)
    输出
    My favorite foods are:
    ['pizza', 'falafel', 'carrot cake', 'cannoli', 'ice cream']
    My friend's favorite foods are:
    ['pizza', 'falafel', 'carrot cake', 'cannoli', 'ice cream']
    两个列表的值始终相同
     
     
    参考4.4.3节
     
     
     
  • 相关阅读:
    python数据类型:字典Dictionary
    python数据类型:元组
    python数据类型:列表List和Set
    python数据类型:字符串
    python数据类型:Number数字
    Python控制语句
    Python运算符
    python基础语法
    Linux shell Script初识
    linux awk详解
  • 原文地址:https://www.cnblogs.com/jingxin-gewu/p/13252950.html
Copyright © 2011-2022 走看看