1、index()方法在列表中查找值
列表值有一个index()方法,可以传入一个值,如果该值存在于列表中,就返回它的下标。如果该值不在列表中,Python 就报ValueError。
>>> spam = ['hello', 'hi', 'howdy', 'heyas']
>>> spam.index('hello')
0
>>> spam.index('heyas')
3
>>> spam.index('howdy howdy howdy')
Traceback (most recent call last):
File "<pyshell#31>", line 1, in <module>
spam.index('howdy howdy howdy')
ValueError: 'howdy howdy howdy' is not in list
如果列表中存在重复的值,就返回它第一次出现的下标。
>>> spam = ['Zophie', 'Pooka', 'Fat-tail', 'Pooka']
>>> spam.index('Pooka')
1
2、append()和insert()方法在列表中添加值
append()方法调用,将参数添加到列表末尾。insert()方法可以在列表任意下标处插入一个值。insert()方法的第一个参数是新值的下标,第二个参数是要插入的新值。
append()方法
>>> spam = ['cat', 'dog', 'bat']
>>> spam.append('moose')
>>> spam
['cat', 'dog', 'bat', 'moose']
insert()方法
>>> spam = ['cat', 'dog', 'bat']
>>> spam.insert(1, 'chicken')
>>> spam
['cat', 'chicken', 'dog', 'bat']
3、remove()方法删除
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam.remove('bat')
>>> spam
['cat', 'rat', 'elephant']
如果该值在列表中出现多次,只有第一次出现的值会被删除。
>>> spam = ['cat', 'bat', 'rat', 'cat', 'hat', 'cat']
>>> spam.remove('cat')
>>> spam
['bat', 'rat', 'cat', 'hat', 'cat']
如果知道想要删除的值在列表中的下标,del 语句就很好用。如果知道想要从列表中删除的值,remove()方法就很好用。
4、sort()方法将列表中的值排序
>>> spam = [2, 5, 3.14, 1, -7]
>>> spam.sort()
>>> spam
[-7, 1, 2, 3.14, 5]
>>> spam = ['ants', 'cats', 'dogs', 'badgers', 'elephants']
>>> spam.sort()
>>> spam
['ants', 'badgers', 'cats', 'dogs', 'elephants']
也可以指定reverse 关键字参数为True,让sort()按逆序排序。
>>> spam.sort(reverse=True)
>>> spam
['elephants', 'dogs', 'cats', 'badgers', 'ants']
ort()方法对字符串排序时,使用“ASCII 字符顺序”,而不是实际的字典顺序。这意味着大写字母排在小写字母之前。因此在排序时,小写的a 在大写的Z 之后。
>>> spam = ['Alice', 'ants', 'Bob', 'badgers', 'Carol', 'cats']
>>> spam.sort()
>>> spam
['Alice', 'Bob', 'Carol', 'ants', 'badgers', 'cats']
如果需要按照普通的字典顺序来排序,就在sort()方法调用时,将关键字参数key 设置为str.lower。这将导致sort()方法将列表中所有的表项当成小写,但实际上并不会改变它们在列表中的值。
>>> spam = ['a', 'z', 'A', 'Z']
>>> spam.sort(key=str.lower)
>>> spam
['a', 'A', 'z', 'Z']
5、reverse()方法反转列表的值
可以调用reverse()方法快速反转列表中项目的顺序。
>>> spam = [5,2,5,44,8,4,1]
>>> spam.sort()
>>> spam
[1, 2, 4, 5, 5, 8, 44]
>>> spam.reverse()
>>> spam
[44, 8, 5, 5, 4, 2, 1]
6、enumerate()函数
调用enumerate()函数获取列表中各项索引和值,同时获得表项和表项索引。
>>> supp = ['pens', 'staplers','flames','binders']
>>> for index, item in enumerate(supp):
... print('Index'+ str(index) + ' in supp is: ' + item)
...
Index0 in supp is: pens
Index1 in supp is: staplers
Index2 in supp is: flames
Index3 in supp is: binders
7、random.choice()和random.shuffle()函数
random.choice()函数将从列表中返回一个随机选择的表项。
>>> import random
>>> pets=['dogs', 'cats', 'ducks']
>>> random.choice(pets)
'cats'
>>> random.choice(pets)
'dogs'
>>> random.choice(pets)
'cats'
>>> random.choice(pets)
'cats'
>>> random.choice(pets)
'dogs'
>>> random.choice(pets)
'dogs'
random.shuffle()函数将对列表进行重新排序,该函数将就地修改列表,而不是返回新列表。
>>> import random
>>> people=['Alice', 'David', 'Bob', 'Lisa']
>>> random.shuffle(people)
>>> people
['David', 'Alice', 'Lisa', 'Bob']
>>> random.shuffle(people)
>>> people
['David', 'Bob', 'Lisa', 'Alice']