list是处理一组有序项目的数据结构,即你可以在一个列表中存储一个 序列 的项目
列表中的项目应该包括在方括号中,这样Python就知道你是在指明一个列表。一旦你创建了一个列表,你可以添加、删除或是搜索列表中的项目。
由于你可以增加或删除项目,我们说列表是 可变的 数据类型,即这种类型是可以被改变的。
通用序列操作
通用的序列操作包括:索引(indexing),分片(sliceing),加(adding),乘(multiplying)以及检查某个元素是否属于序列的成员。另还有计算序列长度,找出最大元素,最小函数的内建函数
1. 索引
序列中所有元素都有编号--从0开始递增。
indexing = "HelloWelcomeToPython!"
print (indexing[0])
print (indexing[8]) print (indexing[-1])
注:使用负数索引,python会从右边开始计算。最后一个元素的位置编号是-1
2. 分片
使用分片操作来访问一定范围的元素,分片通过冒号相隔的两个索引来实现
numbers = [1,2,2,3,4,5,66,777,8,222,10,101] print (numbers[3:6]) # 获取第4个到第6个元素 print (numbers[-3:]) # 获取最好三个元素 print (numbers[:3]) # 获取前三个元素 print (numbers[0:10:2]) # 步长为2分片 print (numbers[::4]) # 步长为4分片 print (numbers[::-1]) # 从右到左提取元素
序列相加
a = [1,2,3,4,5] b = [6,7,8,9,10] print (a + b)
注:列表不能与字符串相加。即两个相同类型的序列才能进行连接操作
序列相乘
用数字X乘以一个序列会生成一个新的序列。原序列会被重复X次
X = "ILovePython~"
print (X*10)
XX = [111]
print (XX*10)
注:None 是python的内建值,意味着里面没有任何元素(空值)
成员资格
检查一个值是否在序列中,使用in运算符。条件为真,返回值为True,条件为假,返回值为False.
numb = [12,34,54,232,111,3333] print (12 in numb) print (123 in numb)
例子:登录帐号认证
database =[ ["xiaohong","123456"],["xiaoming","111111"],["zhangsan","123344"],["lisi","121212"]] username = input("please input your name:") password = input("please your password:") if [username,password] in database: print ("welcome to login") else: print ("You do not have permission to log on")
长度、最大值、最小值
内建函数len、min、max 分别返回列表的长度、最小值、最大值
lis = [1,22,333,4444,55555,666666,7777777,88888888]
print (len(lis))
print (min(lis)) print (max(lis))
列表的基本操作
1. 改变列表(修改列表的元素,赋值实现)
x = [1, 2, 3, 4, 5, 6 ,7, 8] print (x) x[3] = 444 # 将第四个元素修改为 444 print (x)
2. 删除元素 (使用del 语句)
animals = ["Deer", "Tiger", "Monkey", "Dog", "Pig", "Snake"] print (animals) del animals[2] # 删除第三个元素 print (animals)
3. 分片赋值
name = list("xieshengsen")
print (name)
name[8:] = list("SEN") # 修改多个元素值,并分片显示 print (name)
4. append 用于在列表末尾追加新的对象
fruits = ["peach", "pear", "banana", "watermelon"]
print (fruits) fruits.append("orange") # 在水果列表末尾添上 "orange" print (fruits)
5. count 统计某元素在列表中出现的次数
numbers = [1 , 2, 2, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5] print ("1 出现次数:",numbers.count(1)) print ("2 出现次数:",numbers.count(2)) print ("3 出现次数:",numbers.count(3)) print ("4 出现次数:",numbers.count(4)) print ("5 出现次数:",numbers.count(5)) print ("6 出现次数:",numbers.count(6))
6. extend 在列表的末尾一次性添加另一个序列的多个值
a = [1, 2, 3, 4, 5] b = [66, 77, 88, 99] a.extend(b) print (a) print (b)
7. index 用于从列表中找出某个值第一个匹配项的索引位置
Jobs = ["He", "said", "this", "would", "prevent", "companies", "from", "creating", "new", "jobs"] print (Jobs.index("this")) print (Jobs[2])
8. insert 用于将对象插入到列表
numbs = [1, 2 ,3, 4, 5, 6 ,7] print (numbs) numbs.insert(5, "four") print (numbs)
9. pop 移除列表中一个元素(默认是最后一个)
y = [1 ,2, 3, 4, 5, 6, 7, 8] y1 = y.pop() # 默认移除最后一个函数 print (y1) # print (y) y2 = y.pop(1) # 移除第二个函数 print (y2) print (y)
10. remove 移除列表中某个值的第一个匹配项
QAZ = ["qq", "ww", "ee", "rr", "aa", "ss"] QAZ.remove("ww") print (QAZ)
注:remove 是一个没有返回值的原位置改变方法。修改列表后没有返回值,与pop方法相反。
11. reverse 将列表中的元素反向存放
A = [1, 2, 3, 4, 5] A.reverse() print (A)
12. sort 用于将原位置的列表进行排序。
num = [3 , 4, 2, 1, 7, 6, 9, 8] num.sort() print (num) letter = ["b", "d", "a", "c", "f", "e", "g"] letter.sort() print(letter)
sort 方法有另外两个可选的参数:key 和 reverse.
AAA = ["BB","DDDD","A","EEEEE","CCC"] AAA.sort(key=len) print (AAA) BBB = [3, 5, 10, 8, 1, 4, 7] BBB.sort(reverse=True) # 当reverse=false 列表相反排列 print(BBB)
list 官方文档常用解析
class list(object):
""" list() -> new empty list list(iterable) -> new list initialized from iterable's items """ def append(self, p_object): # real signature unknown; restored from __doc__ """ L.append(object) -- append object to end """ pass def count(self, value): # real signature unknown; restored from __doc__ """ L.count(value) -> integer -- return number of occurrences of value """ return 0 def extend(self, iterable): # real signature unknown; restored from __doc__ """ L.extend(iterable) -- extend list by appending elements from the iterable """ pass def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__ """ L.index(value, [start, [stop]]) -> integer -- return first index of value. Raises ValueError if the value is not present. """ return 0 def insert(self, index, p_object): # real signature unknown; restored from __doc__ """ L.insert(index, object) -- insert object before index """ pass def pop(self, index=None): # real signature unknown; restored from __doc__ """ L.pop([index]) -> item -- remove and return item at index (default last). Raises IndexError if list is empty or index is out of range. """ pass def remove(self, value): # real signature unknown; restored from __doc__ """ L.remove(value) -- remove first occurrence of value. Raises ValueError if the value is not present. """ pass def reverse(self): # real signature unknown; restored from __doc__ """ L.reverse() -- reverse *IN PLACE* """ pass def sort(self, cmp=None, key=None, reverse=False): # real signature unknown; restored from __doc__ """ L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*; cmp(x, y) -> -1, 0, 1 """ pass