中国建筑网官方网站入口,上海市建设工程咨询网,静态网站 分页,手机网站商城建设答辩问题-*-列表是新手可直接使用的最强大的python功能之一#xff0c;它融合了众多重要的编程概念。-*-# -*- coding:utf-8 -*-# Author:sweeping-monkQuestion_1 什么是列表#xff1f;print(Question_1)smg 列表由一系列按特定顺序排列的元素组成。你可以创建…-*-列表是新手可直接使用的最强大的python功能之一它融合了众多重要的编程概念。-*-# -*- coding:utf-8 -*-# Author:sweeping-monkQuestion_1 什么是列表print(Question_1)smg 列表由一系列按特定顺序排列的元素组成。你可以创建包含所有字母数字0—9或者所有小组成员的列表也可以将任何东西加入列表其中元素之间没有任何关系。print(smg)Method_1 在python中用([])来表示列表用逗号来分隔其中的元素。下面用一个简单的例子来说明print(Method_1)name [zhangsan,lisi,wangwu,678,张扬]print(name)Question_2 如何访问列表元素print(Question_2)smg2 列表是有序集合要访问列表任何元素只需将该元素的位置和索引告诉python就可以在python中第一个列表元素的索引为0而不是1。python为访问最后一个列表元素提供了特殊的语法通过将索引指定为-1可让python返回最后一个列表元素这中语法很有用。print(smg2)Method_2 具体请看下面的程序print(Method_2)name1 [zhangsan,lisi,wangwu,678,张扬]print(name1[0]) #第一个列表元素的索引为0。print(name1[1])print(name1[-1]) #特殊语法print(name1[-2])print(name1[0].title()) #加方法可以使用户看到的结果---整洁干净。message my name is name1[-3].title() ! #从列表中取元素拼接一句话。print(message)Chicken_soup 工作中你创建的列表大多都是动态的这意味着列表创建后将随着程序的运行增删元素print(Chicken_soup)Modify_list_elements [zhangsan,lisi,wangwu]print(Modify_list_elements)Modify_list_elements[0] xiaole #修改列表中第一个元素。print(Modify_list_elements)Add_list_elements []Add_list_elements.append(zhangshan) #在空列表中添加元素。Add_list_elements.append(lisi)Add_list_elements.append(wangwu)print(Add_list_elements)Add_list_elements.append(xiaole) #在列表元素末尾添加元素。print(Add_list_elements)Add_list_elements.insert(0,sunyuan) #在列表第一个元素前面添加元素。print(Add_list_elements)Add_list_elements.insert(2,huahua) #在列表第三个元素前面添加元素。print(Add_list_elements)del Add_list_elements[1] #使用del可删除任意位置处的列表元素条件是你必须先知道其元素所在列表中的位置(索引)。print(Add_list_elements)Weed_out_the_bottom [sunyuan,xiaole,jitao,huahua]print(Weed_out_the_bottom)popped_the_bottom Weed_out_the_bottom.pop() #方法pop(),pop(术语弹出)可删除列表末尾的元素并让你能够接着使用被删除的元素值。print(Weed_out_the_bottom) #在列表中显示是否剔除了末位。print(popped_the_bottom) #把末位被剔除的谁给打印出来Chicken_soup_1 列表就像一个栈而删除列表末尾的元素就相当于弹出栈顶的元素。print(Chicken_soup_1)popup [zhansan,lisi,wangwu,xiaole]print(popup)popup_1 popup.pop(1) #弹出列表中任意位置的元素这里弹出列表中第二位置的元素。print(popup)print(popup_1)popup_2 popup.pop(0) #弹出列表中任意位置的元素这里弹出列表中第一位置的元素。print(popup)print(popup_2)Chicken_soup_2 凡事要举一反三多纬度思考前面我们是根据元素位置信息来删除元素反之也可以根据元素值来删除元素。The_delete [zhangsan,lisi,wangwu,xiaole]print(The_delete)The_delete.remove(wangwu) #不知道元素位置但知道位置值可以用这种方法删除。print(The_delete)The_delete_1 [zhangsan,lisi,wangwu,xiaole]print(The_delete_1)my_favorite_person xiaole #使用remove()从列表中删除元素时也可以接着使用它的值。The_delete_1.remove(my_favorite_person)print(The_delete_1)print(\n my_favorite_person.title() is my favorite person.)Chicken_soup_3 方法remove()只删除第一个指定的值如果要删除的值可能在列表中多次出现就需要使用while循环来判断是否删除了所有这样的值。pets [dog,cat,dog,goldfish,cat,rabbit,cat]print(pets)while cat in pets: #使用while in 循环来逐个删除多个cat。pets.remove(cat)print(pets)