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. android——TextView默认文字开发时显示运行时隐藏

    根布局添加属性: xmlns:tools="http://schemas.android.com/tools" textview添加属性: tools:text="默认文 ...

  2. TP多条件查询实例

    where条件查询,时间范围查询 $condition = [ ['member_id', '=', $member_id] ]; if($type) { $condition[] = ['type' ...

  3. idea xml文件去掉背景黄色

    编写dao中的sql时,xml文件中背景一大片黄色,看着不舒服,如何去掉了? 1. File -> Settings... 2. 去消以下两项勾选    (Inspections    -- 如 ...

  4. 恒生UFX交易接口基本介绍

    https://zhidao.baidu.com/question/203296047903136445.html 1.恒生UFT和UFX有什么区别? UFT是一个极速交易系统,UFX是一个统一接入系 ...

  5. 求1+2+3+…..+n

    [问题]求1+2+3+…+n,要求不能使用乘除法.for.while.if.else.switch.case等关键字及条件判断语句(A?B:C). [思路]由于题目好多运算符不能用,我们只有想到使用递 ...

  6. Django1.11基础视图

    Django视图 路由命名与reverse反解析 在项目urls中的include函数,使用namespace参数定义路由命名空间 url(r'^',incude('book.urls',namesp ...

  7. Java之创建线程的方式四:使用线程池

    import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.c ...

  8. js判断苹果和安卓端或者wp端

    最近做了一个H5,说要提供一个底部,可以区分安卓或者ios,到相应的网址进行下载APP,如图: 代码如下:  window.onload = function () { var u = navigat ...

  9. Linux--shell 脚本免密码输入

    参考:https://www.cnblogs.com/lixigang/articles/4849527.html #!/bin/bash ssb=" password=mysql data ...

  10. salt-stack 常用state模块

    /xxx/xxxx/filename: file.managed:                                                       文件管理模块:可以将ma ...