python 列表
列表切片
列表切片可以从列表中获取多个值,结果是一个新的列表。格式:spam[:]
第一个整数是切片开始处的下标,第二个整数时切片结束处的整数。切边向上增长但是不包括第二个下标的值。
spam=['cat','dog','horse','lion']
print(spam[0:4])#列表中下标从0到3的数
print(spam[1:3])#列表中下标从1到2的数
print(spam[0:-1])#列表中下标从0到倒数第一位的数(不包括最后一位)
结果:
['cat', 'dog', 'horse', 'lion']
['dog', 'horse']
['cat', 'dog', 'horse']
为了方便,可以省略冒号旁边的数字。
省略第一个数字代表从0开始(即列表的开始)。省略第二个下标相当于省略列表的长度,即列表的末尾。
spam=['cat','dog','horse','lion']
print(spam[:2])
print(spam[1:])
print(spam[:])
结果:
['cat', 'dog']
['dog', 'horse', 'lion']
['cat', 'dog', 'horse', 'lion']
负数下标
python列表的下标也可以用负数。负几就代表倒数第几位。
例:
spam=['cat','dog','horse','lion']
print(spam[-1])
print(spam[-3])
结果:
lion
dog
从列表删除值
del
spam=['cat','dog','horse','lion']
del spam[2]
结果:
spam=['cat','dog','lion']
del spam[2]
结果:
spam=['cat','dog']
remove()
给remove()方法传入一个值,它会在调用的列表中删除。
注意:如果列表中多次出现这个值,只有第一次会被删除。
spam=['cat','dog','horse','lion','cat']
spam.remove('cat')
spam
结果:
['dog', 'horse', 'lion', 'cat']
index()在列表中查找值
spam=['cat','dog','horse','lion']
spam.index('dog')
结果:
1
spam.index('lion')
结果:
3
注意:如果列表中有多个值,将会返回第一次时出现的下标.
append()和insert()方法在列表中添加值
append()方法,将参数添加在列表的末尾。
insert()方法,可以将参数插入在指定的位置。
注意:此两种方法返回值为NONE,使用之后,列表的值就被"当场"修改了。
spam=['cat','dog','horse','lion']
spam.append('fish')
spam
结果:
spam=['cat','dog','horse','lion','fish']
spam=['cat','dog','horse','lion']
spam.insert(4,'fish')
spam
结果:
['cat', 'dog', 'horse', 'lion', 'fish']
sort()方法将列表的值排序
spam=[2,5,3,1,7,6]
spam.sort()
spam
结果:
[1, 2, 3, 5, 6, 7]
spam=['cat','dog','horse','lion']
spam.sort()
spam
结果:
['cat', 'dog', 'horse', 'lion']
也可以指定关键字reverse为true,让列表反向排序
spam=[2,5,3,1,7,6]
spam.sort(reverse=True)
spam
结果:
[7, 6, 5, 3, 2, 1]
注意:
1:sort()排序是对列表的当场排序,没有返回值。
2:sort()不能排序既有字符串又有数字的列表。
3:sort()对字符串排序使用ASCII 字符排序,而不是实际的字典顺序。即大写字母排在小写字母之前。
如果想要实际的字典顺序,则修改关键字key的值为str.lower
例:
spam=['cat','Dog','horse','Lion']
spam.sort()
spam
结果:
['Dog', 'Lion', 'cat', 'horse']
spam=['cat','Dog','horse','Lion']
spam.sort(key=str.lower)
spam
结果:
['cat', 'Dog', 'horse', 'Lion']