python实现对列表的增删查修操作
#定义一个空列表 list_demo=[] #1,向列表中插入元素 def append_demo(): #第一种使用append,可以在列表末尾添加一个函数 for i in range(2): list_demo.append(input()) #输入one,two print(list_demo) #["one","two"] #append_demo() def extend_demo(): #第二种使用extend,可以在列表末尾添加多个元素 list_one=[input() for i in range(2)] #输入测试列表["one","two","three"] list_demo.extend(list_one) print(list_demo) #["one","two","three"] # extend_demo() def insert_demo(): #第三种使用insert来完成,可以插入到列表中任一位置 list_demo=["zero","one","two"] list_demo.insert(1,"text_demo") print(list_demo) #['zero', 'text_demo', 'one', 'two'] # insert_demo() #2,删除列表元素 def remove_demo(): #remove删除函数可以删除任一指定的元素 list_demo=["one","two","three"] list_demo.remove("one") print(list_demo) #['two', 'three'] #remove_demo() def pop_demo(): #pop删除列表指定位的元素 list_demo = ["one", "two", "three"] ele_one=list_demo.pop(1) #列表删除并返回该元素 print(ele_one) #two print(list_demo) #['one', 'three'] # pop_demo() def del_dmeo(): #del可以直接删除列表中指定位置的元素 list_demo=["zero","one", "two", "three"] del list_demo[1:3] print(list_demo) #['zero', 'three'] # del_dmeo() #3,查找列表元素 def in_demo(): #通过in和not in 来判断一个元素是否在列表中 list_demo=["zero","one", "two", "three"] if "one" in list_demo: print("yes") #yes if "good" not in list_demo: print("good") #good # in_demo() def count_demo(): #count可以返回元素在列表中出现的次数 list_demo = ["zero", "one", "two", "three"] num=list_demo.count("three") print(num) #1 # count_demo() def index_demo(): #index可以返回元素出现在列表中的位数 list_demo = ["zero", "one", "two", "three"] num=list_demo.index("two") print(num) #2 # index_demo() #4,对列表内的函数的修改 def change_demo(): #修改列表函数直接重新赋值即可 list_demo = ["zero", "one", "two", "three"] list_demo[0]="good" print(list_demo) #['good', 'one', 'two', 'three'] change_demo()