python提供了一个被称为列表的数据类型,他可以存储一个有序的元素集合。
记住:一个列表可以存储任意大小的数据集合。列表是可变对象,有别于字符串str类,str类是不可变对象。
list1 = list() #创建一个空列表 list2 = list([2,3,4]) #创建列表,包含元素2,3,4 list3 = list(["red","green"]) #创建字符串列表 list4 = list(range(3,6)) list5 = list("abcd")
list1 = list[]
list2 = list[2,3,4]
操作 | 描述 |
x in s | 如果元素x在序列在s中则返回true |
x not in s | 如果元素x在序列不在s中则返回true |
s1 + s2 | 连接两个序列s1和s2 |
s*n, n*s | n个序列s的连接 |
s[ i ] | 序列s的第 i 个元素 |
s[ i, j ] | 序列s从下标 i 到 j-1 的片段 (列表截取) |
len(s) | 序列s的长度,即s中的元素个数 |
min(s) | 序列s的最小元素 |
max(s) | 序列s的最大元素 |
sum(s) | 序列s中所有元素之和 |
for loop | 在for循环中从左到右反转元素 |
<,<=,>,>=,=,!= | 比较两个序列,若真则返回true |
random.shuffle(s) | 随意排列序列s中的元素 |
>>>mylst= [0,1,2,3,4,5] >>>mylst[2,4] [2, 3]
>>>mylist[:3] [0, 1, 2] >>>mylist[2:] [2, 3, 4, 5] >>>mylist[:] [0, 1, 2, 3, 4, 5] >>>mylist[-4:-2] [2, 3]
>>>mylist[3:2] #start > end ,则会报错 Traceback (most recent call last): File "<pyshell#1>", line 1, in <module> mylist[3:2] NameError: name ‘mylist‘ is not defined
>>>list1 = [x for x in range(5)] >>>list1 [0, 1, 2, 3, 4] >>>list2 = [0.5*x for x in list1] >>>list2 [0.0, 0.5, 1.0, 1.5, 2.0] >>>list3 = [x for x in list2 if x < 1.5] >>>list3 [0.0, 0.5, 1.0]
append(x: object) :None | 将元素添加到列表结尾 |
count(x: object): int | 返回元素x在列表中出现的次数 |
extend(lst: list): None | 将列表 l 中的所有元素追加到列表中 |
index(x: object): int | 返回x在列表中第一次出现的下标 |
insert(index: int, x:object):None | 将元素x插入列表中指定下标处 |
pop(i): object | 删除给定位置的元素并返回它。参数 i 可选,若没有指定,则删除并返回列表中的最后一个元素 |
remove(x: object): None |
删除列表中第一次出现的x |
reverse(): None | 将列表中的所有元素倒序(不是排序) |
sort(): None | 将列表中的元素升序排序(注意:是排序) |
>>> list1 = [2, 3, 4, 1, 32, 4] >>> list1.append(19) >>> list1 [2, 3, 4, 1, 32, 4, 19] >>> list1.count(4) 2 >>> list2 = [99, 54] >>> list2.extend(list1) >>> list2 [99, 54, 2, 3, 4, 1, 32, 4, 19] >>> list2.index(4) 4 >>> list2.insert(1, 25) >>> list2 [99, 25, 54, 2, 3, 4, 1, 32, 4, 19] >>> list2.pop() #删除最后一个位置的元素 19 >>> list2 [99, 25, 54, 2, 3, 4, 1, 32, 4] >>> list2.pop(2) #删除指定位置的元素,这里删除下标为2的元素 54 >>> list2 [99, 25, 2, 3, 4, 1, 32, 4] >>> list2.remove(4) >>> list2 [99, 25, 2, 3, 1, 32, 4] >>> list2.reverse() #将原序列倒过来 >>> list2 [4, 32, 1, 3, 2, 25, 99] >>> list2.sort() #将原序列升序排序 >>> list2 [1, 2, 3, 4, 25, 32, 99]
原文:http://www.cnblogs.com/libra-yong/p/6250214.html