生活所迫学习python 第三篇

第一个数据结构

1列表(list

1.1列表的概念:

    列表是处理一组有序元素的数据结构。列表的长度和元素都是可以改变的。

1.2列表的格式:

列表名称=[元素1,元素2, …]

2个重点:

1 []方括号包起来

2 元素间用,逗号分隔

 

2 列表的相关的方法:

2.1 追加一个新元素到列表的尾巴上

list.append(x)

实例:

#!/usr/bin/python

 

list1=[1,2,3,4,5]

print list1

list1.append(6)

输出:

[1, 2, 3, 4, 5]

[1, 2, 3, 4, 5, 6]

2.2 扩展这个列表,通过后面再追加输入参数的列表

list.extend(L)

实例:

#!/usr/bin/python

 

list1=[1,2,3,4,5]

list2=[6,7,8,9,10]

print list1

list1.extend(list2)

print list1

输出:

[1, 2, 3, 4, 5]

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

2.3在指定的位置插入一个元素

list.insert(i, x)

#!/usr/bin/python

 

list1=[1,2,3,4,5]

print list1

list1. insert (3,9) 在第三个位置的后面插入9这个数字

print list1

输出:

[1, 2, 3, 4, 5]

[1, 2, 3, 9, 4, 5]

2.4 删除列表里面出现的第一个给出要删除的值

list.remove(x)

实例:

#!/usr/bin/python

 

list1=[1,2,3,4,5]

print list1

list1. remove (3)

print list1

输出:

[1, 2, 3, 4, 5]

[1, 2, 4, 5]

2.5 从队列里移除,并返回指定的元素,类似于弹栈操作,如果不指定的话就会把最后一个弹出来

list.pop([i])

实例:

#!/usr/bin/python

 

list1=[1,2,3,4,5]

print list1

n=list1.pop()

print n

输出:

[1, 2, 3, 4, 5]

2.6返回第一个出现的x值的index(位置)

list.index(x)

实例:

#!/usr/bin/python

 

list1=[1,2,3,3,5]

print list1

n=list1. index ()

print n

输出:

[1, 2, 3, 3, 5]

2

2.7 统计x出现的次数

list.count(x)

实例:

#!/usr/bin/python

 

list1=[1,2,3,3,5]

print list1

n=list1. count ()

print n

输出:

[1, 2, 3, 3, 5]

2.8 列表排序

list.sort()

实例:

#!/usr/bin/python

 

List4=[2,1,3,5,4]

print list1

list4.sort()

print list4

输出:

[2,1,3,5,4]

[1, 2, 3,4, 5]

2.9列表翻转

list.reverse()

实例:

#!/usr/bin/python

 

List1=[1,2,3,4,5]

print list1

list1. reverse ()

print list1

输出:

[1,2,3,4,5]

[5,4,3,2,1]

 

Python 手册上的总结表格:

Operation

Result

s[i] = x

item i of s is replaced by x

s[i:j] = t

slice of s from i to j is replaced by the contents of the iterable t

del s[i:j]

same as s[i:j] = []

s[i:j:k] = t

the elements of s[i:j:k] are replaced by those of t

del s[i:j:k]

removes the elements of s[i:j:k] from the list

s.append(x)

same as s[len(s):len(s)] = [x]

s.extend(x)

same as s[len(s):len(s)] = x

s.count(x)

return number of i‘s for which s[i] == x

s.index(x[, i[, j]])

return smallest k such that s[k] == x and i <= k < j

s.insert(i, x)

same as s[i:i] = [x]

s.pop([i])

same as x = s[i]; del s[i]; return x

s.remove(x)

same as del s[s.index(x)]

s.reverse()

reverses the items of s in place

s.sort([cmp[, key[, reverse]]])

sort the items of s in place

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值