Python——列表(List)
List
(列表)由一系列按特定顺序排列的元素组成 ,是Python
中使用最频繁的数据类型,可以创建包含字母表中所有的字母、数字0-9;也可以将任何东西加入列表中,其中元素之间可以没有任何关系。在Python中,用方括号
[]
来表示列表,并用逗号来分隔其中的元素,列表的索引是从0
开始,类似于java中的数组。
#一个简单的定义列表
bicycles = ['trek','cannondale','redline','specialized']
print(bicycles)
['trek', 'cannondale', 'redline', 'specialized']
-
列表常用的操作
-
在
ipython3
中定义一个列表,例如:name_list = []
-
输入
name_list.
按下TAB
键,ipython
会提示列表 能够使用的方法如下name_list.append name_list.index name_list.remove name_list.count name_list.insert name_list.reverse name_list.extend name_list.pop name_list.sort
-
-
append:在列表未尾追加一个元素
name_list.append('lisi') print(name_list) ['lisi']
-
index:根据元素获取他的下标索引
In [10]: name_list.index('lisi') Out[10]: 0
-
remove:删除指定的元素
name_list('lisi')
-
count:数据在列表中出现的次数
In [24]: print(name_list) ['aa', 'bb', 'cc', 'cc'] In [25]: name_list.count('aa') Out[25]: 1 In [26]: name_list.count('cc') Out[26]: 2
-
insert:在指定位置添加一条元素
In [27]: name_list.insert(1,'python') In [28]: print(name_list) ['aa', 'python', 'bb', 'cc', 'cc']
-
reverse:返回列表中的元素
In [30]: name_list.reverse() In [31]: print(name_list) ['cc', 'cc', 'bb', 'python', 'aa']
-
extend:继承
In [32]: name_list1 = [] In [33]: name_list1.extend(name_list) In [34]: print(name_list1) ['cc', 'cc', 'bb', 'python', 'aa']
-
pop:删除列表未尾的元素,并返回
In [37]: print(name_list) ['cc', 'cc', 'bb', 'python', 'aa'] In [38]: ret = name_list.pop() In [39]: print(ret) aa In [40]:
-
sort:给列表中的元素,按字母排序
In [40]: name_list.sort() In [41]: print(name_list) ['bb', 'cc', 'cc', 'python'] In [42]:
-
del:根据索引删除指定的元素
In [41]: print(name_list) ['bb', 'cc', 'cc', 'python'] In [42]: del name_list[1] In [43]: print(name_list) ['bb', 'cc', 'python'] In [44]:
-
遍历循环
-
遍历就是从头到尾依次从列表中获取数据
for name in name_list: print(name)
-