访问列表的元素:通过索引下标的方式。print(列表名[下标值])
举例:
list1=[1,2,3,4,5,6] list2=["你好","python","早上好"] print(list1[2]) print(list1[5]) print(list2[2]) print(list2[1])
3 6 早上好 python
列表元素值的修改:可通过直接赋值的方式进行修改。
举例:
list1=[1,2,3,4,5,6] list2=["你好","python","早上好"] list1[2]=99 list1[5]=101 list2[2]="hello" list2[1]="谢谢" print(list1[2]) print(list1[5]) print(list2[2]) print(list2[1])
99 101 hello 谢谢
列表的组合:可通过将两个列表名直接相加打印输出。
举例:
list1=[1,2,3,4,5,6] list2=["你好","python","早上好"] print(list1+list2)
[1, 2, 3, 4, 5, 6, '你好', 'python', '早上好']
判断某个值是否在列表中:使用if—else语句
举例:
list1=[1,2,3,4,5,6] list2=["你好","python","早上好"] if 38 in list1: print("YES") else: print("NO") if "晚上好" in list2: print("晚上好") else: print("FALSE")
NO FALSE
列表元素的截取:采用切片的方式进行。
举例:
list1=[1,2,3,4,5,6] list2=["你好","python","早上好"] print(list1[0:2]) print(list1[:]) print(list2[1:2]) print(list2[:-1])
[1, 2] [1, 2, 3, 4, 5, 6] ['python'] ['你好', 'python']