强烈推荐!!Python系列专栏更多内容汇总可以点击下面跳转链接查看
Python基础语法+算法模板+例题分享专栏导航
个人理解:列表其实就是c++里的vector容器,但是一个列表里可以存各种类型的数据。对列表也有进行的操作和字符串很相似,包括索引,切片,加,乘,检查成员等。
list1 = ['physics', 'chemistry', 1997, 2000]
list2 = [1, 2, 3, 4, 5 ]
list3 = ["a", "b", "c", "d"]
与字符串的索引一样,列表索引从0开始。列表可以进行截取、组合等。
list1 = ["abc", "def", "ghi", "jkl"]
list2 = ["123", "456", "789", 1990]
print(list1[0])
print(list2[0:-1])
输出结果为:
abc
[‘123’, ‘456’, ‘789’]
list = []
list.append("sjh")
print(list)
list[0] = "zym"
print(list)
注意:如果初始列表为空,即list = [],那么只能先通过list.append("balabala")为其增加数据,当列表为空时,使用list[0] = "balabala" 则会造成访问越界(因为没有0号索引)
list = ['physics', 'chemistry', 1997, 2000]
print(list)
del list[2]
print(list)
输出结果为:
[‘physics’, ‘chemistry’, 1997, 2000]
[‘physics’, ‘chemistry’, 2000]
list = ["sjh", "zym", "abc"]
obj = list.pop(0); #删除0号索引的元素,返回值赋给obj
print(obj)
print(list)
list.pop(); #默认删除列表最后一个元素,返回值可以不被变量接收
print(list)
输出结果:
sjh
[‘zym’, ‘abc’]
[‘zym’]
注意:list.pop(index)会返回删除的对象,返回值可以不被变量接收,当遇到需要拿一个元素,拿完后删除时,可以使用该操作
list = ["sjh", "sjh", "zym", "abc", 123]
list.remove("sjh")
print(list)
输出结果:
[‘sjh’, ‘zym’, ‘abc’, 123]
注意:此方法是根据对象名删除,当遇到一个列表里有多个相同的对象时,只删除最前面的那一个,上面的例子很好的体现了这一点
list = ["sjh", "zym", "abc"]
list.insert(0, "sjh")
print(list)
输出结果:
[‘sjh’, ‘sjh’, ‘zym’, ‘abc’]
注意:list.insert其实也是更新列表,并且他可以给空列表进行insert,并且对空列表进行insert时,不管index是几,都会给列表的0号索引添加insert的对象
alist = ["sjh", "sjh", "zym", "abc"]
blist = [123, 456, 789]
alist.extend(blist)
print(alist)
输出结果:
[‘sjh’, ‘sjh’, ‘zym’, ‘abc’, 123, 456, 789]
list = [123, 456, 789]
list.reverse()
print(list)
输出结果:
[789, 456, 123]
参数含义如下:
key – 它是一个函数,功能有两个
(1)该函数接受一个列表中的元素作为输入,并返回一个用于排序的键。如果指定了key,那么排序过程将key的函数返回的内容作为键,根据这个键来进行排序
(2)该函数返回一个排序规则, 排序时根据该规则排序
reverse – 排序规则,reverse = True 降序, reverse = False 升序(默认为升序)
实例1(对列表升序排序):
list = [456, 789, 123]
list.sort()
print(list)
输出结果:
[123, 456, 789]
list = ['c', 'b', 'a', 'e', 'd'] #对于字符,排序时根据其asc码大小排序
list.sort(reverse=True) #降序排
print(list)
输出结果:
[‘e’, ‘d’, ‘c’, ‘b’, ‘a’]
# 获取列表的第二个元素
def takeSecond(elem):
return elem[1]
# 列表
random = [(2, 2), (3, 4), (4, 1), (1, 3)]
# 指定第二个元素排序
random.sort(key=takeSecond)
# 输出类别
print('排序列表:%s' % random)
输出结果:
排序列表:[(4, 1), (2, 2), (1, 3), (3, 4)]
该例子通过指定元组的第二个元素作为键升序排序,元组中第二个元素越小,整个元组排序时越在前面。
from functools import cmp_to_key #固定写法,python3中移除了cmp参数,key=cmp_to_key(自己定义的)
# 获取列表的第二个元素
def cmp(x, y):
if x[0] == y[0]:
return x[1] - y[1] #如果两个元组中的第一个元素值相同,则返回第二个元素值大的
else:
return x[0] - y[0] #如果两个元组中的第一个元素值不同,则返回第一个元素值大的
# 列表
list = [(1, 2), (1, 3), (2, 3), (3, 1)]
# 指定cmp为排序规则
list.sort(key=cmp_to_key(cmp))
# 输出
print('排序列表:%s' % list)
输出结果:
排序列表:[(1, 2), (1, 3), (2, 3), (3, 1)]
aList = [123, 'xyz', 'zara', 'abc', 123];
print("Count for 123 : ", aList.count(123))
print("Count for zara : ", aList.count('zara'))
输出结果:
Count for 123 : 2
Count for zara : 1
列表大概就是这些知识点,二维列表什么的后面会单独出一章或者放到题里理解