Python 教程:列表数据类型
列表是 Python 最通用的数据类型,可以编写为用方括号括起来的以逗号分隔的值(元素)列表。使用列表的重要一点是列表的元素不必是相同的类型。即列表的元素(元素)可以是数字、字符串、数组、字典等。甚至列出类型。
创建列表时,可以将值括在方括号中([])并用逗号分隔值。例如 -
list1 = ['physics', 'chemistry', 1990, 2019];
list2 = [1, 2, 3, 4, 5 ];
list3 = ["a", "b", "c", "d"]
Python 与字符串索引类似,列表从 0 开始索引,列表可以进行切片、连接等。
访问列表中的值列表中,使用带索引的方括号或带索引的切片来获取该索引处的值。例如 - #!/usr/bin/python
list1 = ['physics', 'chemistry', 1997, 2000];
list2 = [1, 2, 3, 4, 5, 6, 7 ];
# 第1个元素,返回的是字符串
print "list1[0]: ", list1[0]
# 第2到5个元素,返回的是一个列表
print "list2[1:5]: ", list2[1:5]
Python
#!/usr/bin/python
list1 = ['physics', 'chemistry', 1997, 2000];
list2 = [1, 2, 3, 4, 5, 6, 7 ];
# 第1个元素,返回的是字符串
print "list1[0]: ", list1[0]
# 第2到5个元素,返回的是一个列表
print "list2[1:5]: ", list2[1:5]
执行上述代码会产生以下结果:
list1[0]: physics
list2[1:5]: [2, 3, 4, 5]
Shell更新列表
您可以更新列表左侧的许可证。赋值运算符 一个或多个元素,可以使用 append() 方法添加到列表的元素中。例如 -
#!/usr/bin/python
list = ['physics', 'chemistry', 1997, 2000];
print "Value available at index 2 : "
print list[2]
list[2] = 2001;
print "New value available at index 2 : "
print list[2]
Python 注意 - append() 方法将在后面的章节中讨论。 ? remove()方法,那么就可以使用del语句。例如 -
#!/usr/bin/python
list1 = ['physics', 'chemistry', 1997, 2000];
print list1
del list1[2];
print "After deleting value at index 2 : "
print list1
Python执行上述代码会产生以下结果:
['physics', 'chemistry', 1997, 2000]
After deleting value at index 2 :
['physics', 'chemistry', 2000]
Shell注意 -
方法将在稍后讨论❙♓❙♓remove() 。
基本列表操作
列表像字符串一样对运算符+和*进行反应;也用于串联和迭代,但返回结果计算为 New 列表,而不是字符串。
| Python表达式 | 结果 | 描述 |
|---|---|---|
len([1, 2, 3]) | 3 | 计算列表的长度 |
[1, 64, 5, 64, ] | [1, 2, 3, 4, 5, 6] | 连接两个列表 |
['Hi!'] * 4 | ['Hi!', 'Hi!', 'Hi! !', '嗨!'] | 重复 |
3 in [1, 2, 3] | True | Membership |
for x [1, 2, 3]: print | 1 2 3 | 迭代 |
版权声明
本文仅代表作者观点,不代表Code前端网立场。
本文系作者Code前端网发表,如需转载,请注明页面地址。
上一篇:Python 教程:元组 下一篇:Python 教程:数组概念
code前端网