目录
列表的定义
- 列表是包含0个或多个元素组成的有序列表,属于序列类型。。
- 列表可以对元素进行增加、删除、替换、查找等操作。
- 列表没有长度的限制,元素类型可以不同,不需要预定义长度。
- 列表用“[]”表示,也可以通过list(x)函数将集合或字符串类型转换为列表类型。
>>> a="hello pythhon"
>>> type(a)
<class 'str'>
>>> list(a)
['h', 'e', 'l', 'l', 'o', ' ', 'p', 'y', 't', 'h', 'h', 'o', 'n']
>>> type(a)
<class 'str'>
>>> type(list(a))
<class 'list'>
>>>
列表的索引
- 索引用于获得列表的一个元素,使用中括号[]作为索引的操作符。
- 举例:
>>> lis=[1010,"1010",[1010,"10"],1010]
>>> type(lis)
<class 'list'>
>>> lis[2]
[1010, '10']
>>> lis[-3]
'1010'
>>> lis[-4]
1010
>>> lis[5]
Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module>
lis[5]
IndexError: list index out of range
>>>
- 使用遍历循环对列表元素进行遍历操作,
- 基本格式如下:for <循环变量> in <列表变量> :
- 举例:
>>> lis=[1010,"1010",[1010,"10"],1010]
>>> for i in lis:
print(i)
输出结果:
1010
1010
[1010, '10']
1010
>>> for i in lis:
print(i*2)
输出结果:
2020
10101010
[1010, '10', 1010, '10']
2020
&g