1.列表
是有一系列按特定顺序排列的元素组成。 特点是元素之间没有任何关系,可包含任意类型元素。
大多数列表是动态的(可修改)
列表 由 [ ] 来表示,用逗号分隔
a = [ 'sxd' , 'qwe' , 'asd' ,'ew' ]
print(a)
结果 [ 'sxd' , 'qwe' , 'asd' ,'ew' ]
列表元素
注意 : 列表元素下标从0开始,而不是1.
a = [ 'sxd' , 'qwe' , 'asd' ,'ew' ]
print(a[0])
结果 sxd
访问最后一个元素 -1 ,倒数第二位 -2 以此类推
a = [ 'sxd' , 'qwe' , 'asd' ,'ew' ]
print(a[-1])
结果 ew
使用列表中的某个元素
a = [ 'sxd' , 'qwe' , 'asd' ,'ew' ]
s = "my name is " + a[0].title() + "."
print(s)
结果 my name is Sxd.
修改,添加和删除元素
修改
a = [ 'sxd' , 'qwe' , 'asd' ,'ew' ]
a[0]='123'
print(a)
结果 ['123', 'qwe', 'asd', 'ew']
添加
1)在列表末尾添加元素 (append)
a = [ 'sxd' , 'qwe' , 'asd' ,'ew' ]
a.append('mdm')
print(a)
结果 ['sxd', 'qwe', 'asd', 'ew', 'mdm']
2)在列表中插入元素 (insert)
a = [ 'sxd' , 'qwe' , 'asd' ,'ew' ]
a.insert(1,'ddd')
print(a)
结果 ['sxd', 'ddd', 'qwe', 'asd', 'ew']
3)从列表中删除元素 (del)(pop)(remove)
del使用
a = [ 'sxd' , 'qwe' , 'asd' ,'ew' ]
del a[2]
print(a)
结果 ['sxd', 'qwe', 'ew']
pop使用
a = [ 'sxd' , 'qwe' , 'asd' ,'ew' ]
c = a.pop(1)
print(a)
print(c)
结果 ['sxd', 'asd', 'ew']
qwe
pop与del区别 : 如果不使用表中删除的元素的话用del,还要继续使用所删元素用pop。
根据值删除元素
a = [ 'sxd' , 'qwe' , 'asd' ,'ew' ]
a.remove('qwe')
print(a)
结果 ['sxd', 'asd', 'ew']
组织列表
永久排序 (sort)
默认是按字母大小写排序
cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort()
print(cars)
结果 ['audi', 'bmw', 'subaru', 'toyota']
反方向排序 (sort reverse =True)
cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort(reverse=True)
print(cars)
结果 ['toyota', 'subaru', 'bmw', 'audi']
临时排序 (sorted) :不影响原始排序,原先排序还可以使用。
倒着打印列表 (reverse)
cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.reverse()
print(cars)
结果 ['subaru', 'toyota', 'audi', 'bmw']
确定列表的长度 (len)
cars = ['bmw', 'audi', 'toyota', 'subaru']
c=len(cars)
print(c)
结果 4
循环
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
print(magician)
结果 alice
david
carolina
创建数值列表
for i in range(1,5):
print( i )
结果 1
2
3
4
注意 : 只打印到第二个数停止 (不包含第二个数)
使用range()创建数字列表
可使用list()将range()的结果直接转换为列表
numbers = list(range(1,6))
print(numbers)
结果 [1, 2, 3, 4, 5]
还可以 指定步长 range(1,10,2)意思是打印1-10之间的偶数
将多个数追加到一个列表当中
a=[]
for s in range(1,10):
q = s**2
a.append(q)
print( a )
结果 [1]
[1, 4]
[1, 4, 9]
[1, 4, 9, 16]
[1, 4, 9, 16, 25]
[1, 4, 9, 16, 25, 36]
[1, 4, 9, 16, 25, 36, 49]
[1, 4, 9, 16, 25, 36, 49, 64]
[1, 4, 9, 16, 25, 36, 49, 64, 81]
更简便的
a=[]
for s in range(1,10):
a.append(s**2)
print( a )
列表解析
squares = [value**2 for value in range(1,11)]
print(squares)
结果 [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
切片
[ : ] 全部元素
[-3: ] 最后三个元素
[ :3 ] 第1个到第3个元素
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[0:3])
结果 ['charles', 'martina', 'michael']
元组
列表可以修改,元组不可修改。Python 将不可变得列表称为元组。
定义元组 使用的圆括号
a=(1, 2)
print(a[1])
结果 2
遍历元组
a=(1, 'adsad','dddd')
for i in a:
print(i)
结果 1
adsad
dddd
if 循环
cars = ['audi', 'bmw', 'subaru', 'toyota']
for car in cars:
if car == 'bmw':
print(car.upper())
else:
print(car.title())
结果 Audi
BMW
Subaru
Toyota