-
Python 列表的定义
序列中的每个元素都分配一个数字 - 它的位置,或索引,第一个索引是0,第二个索引是1,依此类推。
1. [] 如:B=[“元素1”,”元素2”]
2.Range 如:list1=list(range(1,3))
Shuffle函数,用于随机排列列表
Python 列表和字符串相互转换
>>> list("Hello")
['H', 'e', 'l', 'l', 'o’]
List1=list(“hello”)
[‘h', 'e', 'l', 'l', 'o'])
>>> "".join(['H', 'e', 'l', 'l', 'o'])
'Hello'>>> ["china",100,"Python","www.xin3721.com"]
['china', 100, 'Python', 'www.xin3721.com’]
>>> range(600)
range(0, 600)
Python 中list 和 range 结合用法
>>> list(range(50))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]
Python访问列表元素
访问列表中元素时,索引是从0开始的。
如
>>> course=["C#","VB.net","SQL Server","JavaScript","CSS"]
print(course[0])
C#Python列表修改、添加、插入和删除元素
course=["C#","VB.net","SQL Server","JavaScript","CSS"]
course[3]="oracle“
print(course[3].title())
Oracle
course=["C#","VB.net","SQL Server","JavaScript","CSS"];course.append("oracle");print(course[5].title())
OraclePython列表修改、添加、插入和删除元素
course=["C#","VB.net","SQL Server","JavaScript","CSS"];
course.insert(0,"oracle");
print(course[0].title())
Oracle
course=["C#","VB.net","SQL Server","JavaScript","CSS"];del course[1];print(course[1].title())
Sql ServerPython列表修改、添加、插入和删除元素
Pop 可以移除列表中的一个元素(默认是最后一个)。
course=["C#","VB.net","SQL Server","JavaScript","CSS"];course.pop();print(len(course))
'CSS’
4
course=["C#","VB.net","SQL Server","JavaScript","CSS"];course.pop(1);print(course[1])
'VB.net'
SQL Server
用remove根据值,删除元素
course=["C#","CSS","VB.net","SQL Server","JavaScript"];course.remove("CSS");print(course[1])
VB.netPython 组织列表
利用sort对列表进行永久性排序
按字母顺序进行正序排列
course=["C#","VB.net","SQL Server","JavaScript","CSS"]
course.sort()
print(course)
['C#', 'CSS', 'JavaScript', 'SQL Server', 'VB.net’]
倒序,则向sort函数传递参数reverse=true
course=["C#","VB.net","SQL Server","JavaScript","CSS"];course.sort(reverse=True);print(course)
['VB.net', 'SQL Server', 'JavaScript', 'CSS', 'C#']使用函数sorted()对列表进行临时排序
course=["C#","VB.net","SQL Server","JavaScript","CSS"]
print(course)
print(sorted(course))
print(course)
如果要显示倒序,可以向sorted传递参数reverse=True
Python的reverse函数
course=["C#","VB.net","SQL Server","JavaScript","CSS"]
print(course)
course.reverse();
print(course)
Python确定列表的长度
使用函数len()可快速获悉列表的长度,前面已经测试过
访问列表最后一个元素
可以用-1这个下标来访问列表中的最后一个元素