列表基础

本章介绍一部分列表方法以及更新列表的一些操作

1. 元素赋值

a=[1,2,3,2,1]
print a
a[1]=10
print a

运行结果:

C:Python27python.exe E:/untitled/zfc/Demo1.py
[1, 2, 3, 2, 1]
[1, 10, 3, 2, 1]

Process finished with exit code 0

2  增加元素

1)方法调用语法 对象.方法(参数)

用append() 方法增加元素

num=[1,2,3]
num.append(4)
print num
num.append(num[0:])
print num

运行结果:

C:Python27python.exe E:/untitled/zfc/Demo1.py
[1, 2, 3, 4]
[1, 2, 3, 4, [1, 2, 3, 4]]

Process finished with exit code 0

3  删除元素

1) 用del方法删除列表中的元素

num=[1,2,3,4]
del num[2]
del num[0:2]
print num


运行结果:

C:Python27python.exe E:/untitled/zfc/Demo1.py
[4]

Process finished with exit code 0

方法  

append()

         

count()

        

extend()

         

index()

         

insert()

         

pop()

         

remove()

         

reverse()

         

 sort() 

        

count() 方法  :用于统计某个元素在列表中出现的次数

           例如:

            num=[1,2,3,1,2,14,12,1]
print num.count(1)

        运行结果:

                      

C:Python27python.exe E:/untitled/zfc/Demo1.py
3

Process finished with exit code 0

extend()方法  :用于在列表末尾一次性追加另外一个序列中的多个值

       例如:

num=[1,2,3,1,2,14,12,1]
num1=[1,2,3,4,5,6,]
num.extend(num1)
print num

运行结果:

C:Python27python.exe E:/untitled/zfc/Demo1.py
[1, 2, 3, 1, 2, 14, 12, 1, 1, 2, 3, 4, 5, 6]

Process finished with exit code 0

index() 方法 : 用于从列表中找出某个值第一个匹配项的索引位置

例如:

num=[1,2,3,1,2,14,12,1]
print num.index(3)

运行结果:

C:Python27python.exe E:/untitled/zfc/Demo1.py
2

Process finished with exit code 0

pop()方法  用于移除列表中一个元素(默认为最后一个元素),并且返回该元素的值

例如:

   

num=[1,2,3,1,2,14,12,1]
print num.pop()

运行结果:

C:Python27python.exe E:/untitled/zfc/Demo1.py
1

Process finished with exit code 0

注:使用pop()方法可以实现数据结构中栈的问题

remove() :用于移除列表中某个值的第一个匹配项

例如:

       

num=[1,2,3,14,12]
num.remove(2)
print num

运行结果:

C:Python27python.exe E:/untitled/zfc/Demo1.py
[1, 3, 14, 12]

Process finished with exit code 0

reverse() 方法: 用于反向列表中的元素

例如:

num=[1,2,3,14,12]
num.reverse()
print num


运行结果:

C:Python27python.exe E:/untitled/zfc/Demo1.py
[12, 14, 3, 2, 1]

Process finished with exit code 0

sort()方法: 用于对原列表进行排序,如果指定参数,就使用参数指定的方法进行比较

例如:

num=[1,2,3,14,12]
num.sort()
print num

运行结果

C:Python27python.exe E:/untitled/zfc/Demo1.py
[1, 2, 3, 12, 14]

Process finished with exit code 0

原文地址:https://www.cnblogs.com/jiangjintao/p/8409624.html