3.列表

2018-05-23  本文已影响0人  恶魔缘

python - 列表

1.列表基本操作

>>> num=[1,2,4]
>>> print(num)
[1, 2, 4]
>>> num.append(6)
>>> print(num)
[1, 2, 4, 6]

>>> num.extend([7,8])
>>> print(num)
[1, 2, 4, 6, 7, 8]
listx = [value**2 for value in range(1,11)]
print(listx)
结果:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
>>> num.insert(0,4)
>>> print(num)
[4, 1, 2, 4, 6, 7, 8]
>>> print(num)
[4, 1, 2, 4, 6, 7, 4, 4, 8]
>>> num[1]
1

listx = [6,7,1,4,7]
print(listx[-1]) //从右往左索引,依次为-1、-2...
结果:
7
>>> list = [1,2,3,4]
>>> list.remove(2) //remove不能删除指定位置的元素
>>> list
[1, 3, 4]
>>> list
[1, 3, 4]
>>> del list[0] //del是一个语句,无需写成del()
>>> list
[3, 4]

>>> listx=[1,2,3,4]  //list是一个关键字,不建议作为变量使用
>>> del listx
>>> listx
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'listx' is not defined
>>> listx=[1,2,3,4]
>>> listx.pop() //把最后一个元素4弹出
4
>>> listx
[1, 2, 3]
>>> listx.pop(0) //弹出指定位置元素
1

2.列表分片

列表分片:使用 隔开两个索引值,左边是开始位置,右边是结束位置,索引值是从0开始的
例如:listx = [0:2]

所谓列表分片,其实是建立了一个原列表的拷贝

分片简写

>>> listx = [1,2,3,4,5]
>>> listx[:]  //仅:表示整个列表
[1, 2, 3, 4, 5]
>>> listx[3:] //结束位不写默认到最后一个元素
[4, 5]
>>> listx[:3] //开始位置默认为0
[1, 2, 3]

通过分片来复制列表

listx = [6,7,1,4,7]
listy = listx[:]
listy.append(8)
print(listx)
print(listy)
结果:
[6, 7, 1, 4, 7]
[6, 7, 1, 4, 7, 8]

2.1列表分片进阶

分片还有第三个参数,表示步长
例如:listx = [0:2:1]

>>> listx=[1,2,3,4,5,6,7,8,9]
>>> listx[::2] //每两个元素才取一个元素出来
[1, 3, 5, 7, 9]

>>> listx[::-1] //表示复制一个反转的分片
[9, 8, 7, 6, 5, 4, 3, 2, 1]


3.分片的操作符

>>> list1=[1,2]
>>> list2=[2,0]
>>> list1>list2 //分片比大小,从第一个元素开始比较,某个元素胜,列表也胜出
False
list1 = [1,2,3]
list2 = [4,5,6]
list3 = list1 + list2
list4 = list1 * 2
print(list3)
print(list4)
结果:
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 1, 2, 3]
list1 = [1,2,[3,4],5]
print(1 in list1)
print(2 not in list1)
print(3 in list1) //in和not in只能判断到第一层列表
print(list1[2][1]) //使用二维数组的方式可访问列表中的列表
结果
True
False
False
4

4.列表的相关方法

查看列表的所有方法:dir(list)

listx = [1,2,3,4,5,6,7,8,8]
print(listx.count(8))
结果:
2
listx = [6,7,1,4,7]
print(len(listx))   #len() 从1开始计算元素个数,不存在差1
结果:
5
listx = [1,2,3,4,5,6,7,8,8]
print(listx.index(8))

# index(key,start,stop) 用于限定查找范围
start = listx.index(8) + 1 //查找第二个元素的位置
stop = len(listx)
print(listx.index(8,start,stop))
结果:
7
8
listx = [1,2,3,4]
listx.reverse()
print(listx)
结果:
[4, 3, 2, 1]
listx = [6,7,1,4,7]
listx.sort() //升序
print(listx)
结果:
[1, 4, 6, 7, 7]
listx = [6,7,1,4,7]
listx.sort(reverse=True) //降序
print(listx)
结果:
[7, 7, 6, 4, 1]
listx = [1,2,3]
print(listx)
listx.clear()
print(listx)
结果:
[1, 2, 3]
[]
listx = [1,2,3]
list1 = listx.copy()
# print(listx,'\n',list1)
print(listx)
print(list1)
结果:
[1, 2, 3]
[1, 2, 3]

5.遍历列表

使用for循环遍历列表

listx = [i for i in range(0,20,3)]
for i in listx:
    print(str(i)+' ',end='')
结果:
0 3 6 9 12 15 18
上一篇下一篇

猜你喜欢

热点阅读