python之列表操作,,#列表操作功能汇总p


#列表操作功能汇总print("列表操作功能汇总")list_demo = [‘first‘, ‘second‘, ‘thrid‘, ‘fourth‘]#复制list_demo列表取名listlist = list_demo[:]print("原列表为:", list)print("-----------------------------")print("输出列表第一个元素:", list[0])print("输出列表最后一个元素:", list[-1])print("从2个开始到第3个输出列表的元素:", list[1:3])print("从2个开始到末尾输出列表的元素:", list[1:])print("-----------------------------")#列表中插入元素至末尾list = list_demo[:]list.append("hello")print("列表中插入元素至末尾:", list)#列表中指定位置插入元素list = list_demo[:]list.insert(1, "hello")print("列表中指定位置插入元素:", list)print("-----------------------------")#删除列表中指定位置的元素list = list_demo[:]del list[1]print("删除列表中指定位置的元素:", list)#删除列表中指定位置的元素并记录list = list_demo[:]popone = list.pop(1)print("删除列表中指定位置的元素并记录:", list, "; 删掉的元素是:", popone)#删除列表中指定值的元素list = list_demo[:]list.remove("first")print("删除列表中指定值的数据:", list)print("-----------------------------")#列表解析:将for循环和表达式的代码合并成一行list = [value**2 for value in range(1, 5)]print("列表解析结果:", list)print("-----------------------------")#检查列表中是否有指定的元素:in或not in。list = list_demo[:]if "first" in list:    print("判断‘first‘在列表中")print("-----------------------------")#判断列表中是否有值if list:    print("判断列表中有值。")else:    print("判断列表为空。")

运行结果:

列表操作功能汇总原列表为: [‘first‘, ‘second‘, ‘thrid‘, ‘fourth‘]-----------------------------输出列表第一个元素: first输出列表最后一个元素: fourth从2个开始到第3个输出列表的元素: [‘second‘, ‘thrid‘]从2个开始到末尾输出列表的元素: [‘second‘, ‘thrid‘, ‘fourth‘]-----------------------------列表中插入元素至末尾: [‘first‘, ‘second‘, ‘thrid‘, ‘fourth‘, ‘hello‘]列表中指定位置插入元素: [‘first‘, ‘hello‘, ‘second‘, ‘thrid‘, ‘fourth‘]-----------------------------删除列表中指定位置的元素: [‘first‘, ‘thrid‘, ‘fourth‘]删除列表中指定位置的元素并记录: [‘first‘, ‘thrid‘, ‘fourth‘] ; 删掉的元素是: second删除列表中指定值的数据: [‘second‘, ‘thrid‘, ‘fourth‘]-----------------------------列表解析结果: [1, 4, 9, 16]-----------------------------判断‘first‘在列表中-----------------------------判断列表中有值。

python之列表操作

评论关闭