Python-List

List


序列是Python中最基本的数据结构。序列中的每个元素都分配了一个数字,称为位置或索引。第一个索引是0,第二个是1…
Python中最常用的序列是List和Tuple;你可以对序列类型执行某些操作,包括索引、切片、添加、乘法和检查成员资格。此外,Python还有用于查找序列长度、最大和最小元素的内置函数。

List

List是Python中最通用的数据类型,仅需要用逗号分隔开列表元素,放在[]内。最重要的是List中的各项不必具有相同类型。
例:

list1 = ['physics', 'chemistry', 1997, 2000]
list2 = [1, 2, 3, 4, 5 ]
list3 = ["a", "b", "c", "d"]

获取List中的值

通过索引可以获取list的值

list1 = ['physics', 'chemistry', 1997, 2000]
list2 = [1, 2, 3, 4, 5, 6, 7 ]
print("list1[0]: ", list1[0])
print("list2[1:5]: ", list2[1:5])

执行结果

list1[0]:  physics
list2[1:5]:  [2, 3, 4, 5]

更新List

可以通过赋值运算符给左侧的索引来更新List元素,并且可以使用append方法向List中添加元素
例:

list = ['physics', 'chemistry', 1997, 2000]
print "Value available at index 2 : "
print(list[2])
list[2] = 2001
print("New value available at index 2 : ")
print(list[2])

执行结果

Value available at index 2 :
1997
New value available at index 2 :
2001

删除List元素

如果知道要删除的元素,可以使用del语句,如果不知道可以使用remove()方法
例:

list1 = ['physics', 'chemistry', 1997, 2000]
print(list1)
del list1[2]
print("After deleting value at index 2 : ")
print(list1)

执行结果

['physics', 'chemistry', 1997, 2000]
After deleting value at index 2 :
['physics', 'chemistry', 2000]

List基本操作

与string类似,+ *于List表示结合与重复操作,与string不同的是结果是一个新List

Python ExpressionResultsDescription
len([1,2,3])3Length
[1,2,3]+[4,5,6][1,2,3,4,5,6]Concatenation
[‘Hi!’] * 4[‘Hi!’, ‘Hi!’, ‘Hi!’, ‘Hi!’]Repetition
3 in [1, 2, 3]TrueMembership
for x in [1, 2, 3]: print x1 2 3Iteration

索引、切片、矩阵

因为List是序列,因此对string适用的索引切片也可以用于List

L = ['spam', 'Spam', 'SPAM!']
Python ExpressionResultsDescription
L[2]SPAM!Offsets start at zero
L[-2]SpamNegative: count from the right
L[1:][‘Spam’, ‘SPAM!’]Slicing fetches sections

List的内置函数与方法

Sr.No.Function with Description
1cmp(list1,list2) Compares elements of both lists
2len(list) Gives the total length of the list
3max(list) Returns item from the list with max value
4min(list) Returns item from the list with min value
5list(seq) Converts a tuple into list

List Method

Sr.No.Methods with Description
1list.append(obj) Appends object obj to list
2list.count(obj) Returns count of how many times obj occurs in list
3list.extend(seq) Appends the contents of seq to list
4list.index(obj) Returns the lowest index in list that obj appears
5list.insert(index,obj) Inserts object obj into list at offset index
6list.pop(obj=list[-1]) Removes and returns last object or obj from list
7list.remove(obj) Removes object obj from list
8list.reverse() Reverses objects of list in place
9list.sort(key=function,reverse=False) Sorts objects of list, key=function optional, reverse default is False
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值