python 列表常用的方法

1.append( ):用于在列表末尾添加新的对象

list.appent(obj)    #obj:添加到列表末尾的对象

#!/usr/bin/python
aList = [123,'xyz','zara','abc']
aList.append(2009)
print("Updated List:",aList) #输出结果:Updated List: [123, 'xyz', 'zara', 'abc', 2009]

extend( ):将列表元素(或任何可迭代的元素)添加到当前列表的末尾

list.extend(obj)      #obj:列表元素或可迭代的元素

#!/usr/bin/python
aList = [123,'xyz','zara','abc']
aList.extend([2009])
print(aList) #输出结果:[123, 'xyz', 'zara', 'abc', 2009]

2. clear( ):删除列表中的所有元素

list.clear( )

#!/usr/bin/python
aList = [123,'xyz','zara','abc']
aList.clear()
print(aList) #输出结果:[]

pop( ):删除指定位置的元素,被删除的值可以继续访问。

list.pop(position)     #position:指定的下标

#!/usr/bin/python
aList = [123,'xyz','zara','abc']
aList.pop(1)
print(aList) #输出结果:[123, 'zara', 'abc']
#列表中的摩托车是按购买时间存储的,就可使用方法pop()打印一条消息,指定最后购买的是哪款摩托车
motorcycles = ['honda','yamaha','suzuki']
last_owned = motorcycles.pop()
print("The last motorcycle I owned was a " + last_owned.title() + ".")
#输出结果:The last motorcycle I owned was a Suzuki.

remove( ):删除具有指定值的项目,当不知道该值所处的位置时。remove只删除第一个指定的值,如果要删除的值可能在列表中出现多次,就需要使用循环来判断是否删除了所有的值。

list.remove(value)    #value:指定的值

#!/usr/bin/python
aList = [123,'xyz','zara','abc']
aList.remove(’xyz')
print(aList) #输出结果:[123, 'zara', 'abc']

  del语句:删除元素,需要知道要删除的元素在列表中的位置。使用del语句将值从列表中删除后,就无法再访问它了。

name = ["crystal","Lily","Lucy","James"]
del name[0]
print(name)
#输出结果:['Lily', 'Lucy', 'James']

3. copy( ):返回列表的副本

#!/usr/bin/python
aList = [123,'xyz','zara','abc']
bList = aList.copy()
print(aList)
print(bList)
#输出结果:[123, 'xyz', 'zara', 'abc']
[123, 'xyz', 'zara', 'abc']

4.count( ):返回具有指定值得元素数量

#!/usr/bin/python
aList = [123,'xyz','zara','abc']
print(aList.count(123)) #输出结果:1

5. insert( ):在指定位置添加元素,需要指定新元素的索引和值

#!/usr/bin/python
aList = [123,'xyz','zara','abc']
aList.insert(1,'crystal')
print(aList) #输出结果:[123, 'crystal', 'xyz', 'zara', 'abc']

6. index( ):返回具有指定值的第一个元素的索引

#!/usr/bin/python
aList = [123,'xyz','zara','abc']
print(aList.index("xyz")) #查找位置,输出结果:1
print(aList[aList.index("xyz")]) #查找位置并打印出来,输出结果:xyz

7. reverse( ):,倒着打印列表,颠倒列表的顺序。reverse永久性修改列表元素的排序,但可以随时恢复到原来的排序,为此只需要对列表再次调用reverse方法即可。

#!/usr/bin/python
aList = [123,'xyz','zara','abc']
aList.reverse()
print(aList) #输出结果:['abc', 'zara', 'xyz', 123]

sort( ):对列表进行永久性排序

#!/usr/bin/python
aList = ['123','xyz','zara','abc']
aList.sort()
print(aList) #输出结果:['123', 'abc', 'xyz', 'zara'],备注:python3中是不能把不同的数据类型进行sort的,会报错
#按照与字母顺序相反的顺序进行排序
cars=['bmw','audi','toyota']
cars.sort(reverse=True)
print(cars)
#输出结果:['toyota', 'bmw', 'audi']

  sorted( ):对列表临时排序,同时不影响它们在列表中的原始排序

cars=['bmw','audi','toyota']
print("Here is the original list:")
print(cars) print("\nHere is the sorted list:")
print(sorted(cars)) print("\nHere is the reverse list:")
print(sorted(cars,reverse = True)) print("\nHere is the original list again:")
print(cars) #输出结果:
Here is the original list:
['bmw', 'audi', 'toyota'] Here is the sorted list:
['audi', 'bmw', 'toyota']

Here is the reverse list:
['toyota','bmw','audi']
Here is the original list again:
['bmw', 'audi', 'toyota']

8. 拼接

name = ["crystal","Lily","Lucy","James"]
message = "The beatiful girl is : "+name[0]
print(message)
#输出结果:The beatiful girl is : crystal

9. 修改列表元素:指定列表名和修改的元素的索引,再指定该元素的新值

name = ["crystal","Lily","Lucy","James"]
name[0]="Mary"
print(name)
#输出结果:['Mary', 'Lily', 'Lucy', 'James']

10. len( ):确定列表长度。python算列表元素数是从1开始。

cars=['bmw','audi','toyota']
print(len(cars))
#输出结果:3

11. 使用列表时避免索引错误

cars=['bmw','audi','toyota']
print(cars[3]) #输出结果:IndexError: list index out of range

  

以上部分内容摘录自:https://www.w3school.com.cn/python

Python语言学习:列表常用的方法的更多相关文章

  1. Python - 基本数据类型及其常用的方法之字典和布尔值

    字典 特点:{"key1": value1, "key2":value2}  , 键值对中的值可以为任何数据类型,键不能为列表.字典(无法哈希),布尔值可以为键 ...

  2. Python - 基本数据类型及其常用的方法之元组

    元组 特点:一级元素无法被修改,且不能被增加或者删除. 基本操作: tu = (11, 22, ["aiden", 33, ("qwe", 11)], 77) ...

  3. Python语言学习:字符串常用的方法

    python字符串常用的方法 1. find( ):在字符串中搜索指定的值并返回它被找到的位置,如果没有找到,则返回-1 string.find(value,start,end) #value:必需, ...

  4. Python学习入门基础教程(learning Python)--8.3 字典常用的方法函数介绍

    本节的主要讨论内容是有关dict字典的一些常用的方法函数的使用和范例展示. 1. clear清除字典数据 语法结构如下: dict_obj.clear() 示例代码如下: dict1 = {'web' ...

  5. Python学习之==>常用字符串方法

    1.常用字符串方法 a = '\n 字 符 串 \n\n' b = a.strip() # 默认去掉字符串两边的空格和换行符 c = a.lstrip() # 默认去掉字符串左边的空格和换行符 d = ...

  6. python语言学习

    前段时间要做视频直播需要编写自动模块,就考虑使用python脚本语言,python的好多语法都是很独特的,比如数据类型不需要预定义,缩进的方式等,另外功能也很强大,豆瓣就是用python写的.我写的部 ...

  7. Python语言学习之C++调用python

    C++调用python 在C/C++中嵌入Python,可以使用Python提供的强大功能,通过嵌入Python可以替代动态链接库形式的接口,这样可以方便地根据需要修改脚本代码,而不用重新编译链接二进 ...

  8. python语言(二)列表、字典、集合、文件读写、关系测试

    1.列表 list   代码 s = '王宇建,苏红,邹存才...' # 列表 数字 list l = ['王宇建','苏红','邹存才'] # 一维数组 二维数组 三维数组 # 0 1 2 # 索引 ...

  9. Python语言学习之Python入门到进阶

    人们常说Python语言简单,编写简单程序时好像也确实如此.但实际上Python绝不简单,它也是一种很复杂的语言,其功能特征非常丰富,能支持多种编程风格,在几乎所有方面都能深度定制.要想用好Pytho ...

随机推荐

  1. Vue.js(20)之 封装字母表(是这个名字吗0.0)

    HTML结构: <template> <div class="alphabet-container"> <h1>alphabet 组件</ ...

  2. 由于TableView的Section的头部和尾部高度设置的不规范引起的部分Section中的图片无法正常显示

    当tableview的组的头部和尾部的高度设置如下时: -(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(N ...

  3. HTML拖放

    <html><head><style>.droptarget {    float: left;     width: 100px;     height: 35p ...

  4. (5)opencv的基础操作和矩阵的掩模操作

    不懂的,可以简单,看看这个网址:https://blog.csdn.net/xiongwen_li/article/details/78503491 图片放到了桌面,所以,图片的路径就是桌面了,剩余的 ...

  5. Maven - pom.xml 文件

    章节 Maven – 简介 Maven – 工作原理 Maven – Repository(存储库) Maven – pom.xml 文件 Maven – 依赖管理 Maven – 构建生命周期.阶段 ...

  6. SQL inner join, join, left join, right join, full outer join

    基本信息 创建两个表a1, a2. 两个表的重要差别是:a1 中有5,'wu',a2中没有. a2中有 4,'li',而a1中没有. 创建表和插入数据的代码如下: -- 创建a1表 create ta ...

  7. redis常用命令--zsets

    zsets常用命令: zadd key score1 mb1 [score2 mb2....]:像key中添加元素和这个元素的分数,如果元素已经存在,则替换分数. zscore key mb :获取k ...

  8. 关于typedef的一些小知识

    //关于typedef //1.在c语言中定义一个结构体typedef struct student{ int a;}stu;//typedef 给结构体起了个别名 stu;//于是,在声明变量的时候 ...

  9. ES6 之 数组的扩展

    ES5 检测数组 let arr = [1,2,3,4] Array.isArray(arr) arr instanceof Array 转换方法 arr.toLocaleString() arr.t ...

  10. vSphere 6.7 新特性 — 基于虚拟化的安全 (VBS)

    https://blogs.vmware.com/china/2018/07/27/vsphere-6-7-%E6%96%B0%E7%89%B9%E6%80%A7-%E5%9F%BA%E4%BA%8E ...