列表相当于Java中的数组,
python
中的列表可以
存储任意类型的元素,同时列表会根据存储内容
动态分配内存。
1 创建列表
1.1 使用[]
创建列表
mylist = ["hello", "word", 98]
print(mylist) # ['hello', 'word', 98]
1.2 使用内置函数list()
创建列表
mylist2 = list(["hello", "word", 2022])
print(mylist2) # ['hello', 'word', 2022]
2 查询元素
2.1 index()
函数
2.1.1 如果列表有多个重复元素,index()
只返回第一个元素的索引。
mylist = ["hello", "word", 98, "hello"]
print(mylist.index("hello")) # 0
2.1.2 如果列表中没有此元素,则会抛出异常。
mylist = ["hello", "word", 98, "hello"]
print(mylist.index("python"))
抛出异常:
Traceback (most recent call last):
File "D:\pythonStudy\fistproject\demo11.py", line 3, in <module>
print(mylist.index("python"))
ValueError: 'python' is not in list
2.1.3 可以指定查询位置。
使用index(obj, start, end)
查询元素位置,从start
到end
前一位,**不包括end
**位置。
mylist = ["hello", "word", 98, "hello"]
print(mylist.index("hello", 1, 4)) # 3
可以看见,查询的范围是:"word", 98, "hello"
。
2.2 获取指定索引位置的元素
和Java
类型,但是要注意一点,python
中索引可以是负数:
- 正向索引:元素从
0
到N-1
- 逆向索引:元素从
-N
到-1
mylist = ["hello", "word", 98, "python"]
# 正向索引
print(mylist[3]) # python
# 逆向索引
print(mylist[-1]) # python
2.3 列表的切片
列表的切片就是列表的拷贝语法为列表名[start: stop: step]
,其中,不包含stop
的元素。
- 切片后的列表,是新的列表,和原列表的ID不一样
- 切片的范围:
[start, stop)
- 步长
step
默认为1 step
为正数时,从start
开始往后切片:[: stop: step]