python数据类型 - 列表list

列表定义

创建数组列表来存放数据,无需声明列表类型,数据自0编号,自下至上放在内存中(堆栈)

  • 列表是有序的元素集合
  • 列表元素可以通过索引访问单个元素
>>> case=[1,2,'文',[3,4,5],'asd']

#索引序列中的元素
>>> case[0]
1
>>> case[2]
'文'
>>> case[3]
[3, 4, 5]
>>>case[3][0]
3

#取子序列,不包含第三位
#分片:从一个列表访问多个列表项(sequence[indexStart : indexEnd : stride])
	#indexstart、indexend确定列表取值的范围
	#stride:表示步长,从Indexstart项跳过stride个列表项,显示出来
>>> case=[1, 2, '文', [3, 4, 5], 'asd', 1, 2, '文', [3, 4, 5], 'asd']
>>> case[1:4]
[2, '文', [3, 4, 5]]
>>> case[0:10:3]
[1, [3, 4, 5], 2, 'asd']
>>> case[0:9:3]
[1, [3, 4, 5], 2]

列表的操作符操作

>>> ca=[1,2,3,[4,5]]
>>> case=[1,2,'文',[3,4,5],'asd']

#连接两个序列
>>> case+ca
[1, 2, '文', [3, 4, 5], 'asd', 1, 2, 3, [4, 5]]

#对序列进行整数次重复
>>> case*2
[1, 2, '文', [3, 4, 5], 'asd', 1, 2, '文', [3, 4, 5], 'asd']

列表的函数操作

>>> case=[1,2,'文',[3,4,5],'asd']

#len:统计列表内数据个数
>>> len(case)

#count:返回x元素在列表中的数量,字符串需要带引号,不然会报错
>>> case.count(1)
1
>>> case.count(asd)
Traceback (most recent call last):
  File "<pyshell#65>", line 1, in <module>
    case.count(asd)
NameError: name 'asd' is not defined
>>> case.count('asd')
1

#index:返回第一次出现元素x的索引值
>>> case.index([3,4,5])
3

#append:将x增加到列表末尾,append只能增加一个数据项,不能增加多个
>>> case.append("增加一个")
>>> case
[1, 2, '文', [3, 4, 5], 'asd', '增加一个']
>>> case.append(1,2)
Traceback (most recent call last):
  File "<pyshell#67>", line 1, in <module>
    case.append(1,2)
TypeError: append() takes exactly one argument (2 given)

#insert:在某个特定位置前面增加一个数据项
>>> case.insert(0,"插入")
>>> case
['插入', 1, '文', [3, 4, 5], 'asd', 666, '999']

#extend在列表末尾增加一个数据集合
>>> case.extend([999,666,'999'])
>>> case
[1, '文', [3, 4, 5], 'asd', 999, 666, '999']

#pop:默认为-1,在列表末尾删除一个数据项,可使用pop(X)删除指定位置X的数据
>>> case.pop()
'增加一个'
>>> case
[1, 2, '文', [3, 4, 5], 'asd']
>>> case.pop(1)
2
>>> case
[1, '文', [3, 4, 5], 'asd']

#remove:在列表中找到特定项并删除(仅删除找到的第一个特定项,列表中其余重复值不删除)
>>> case.remove(999)
>>> case
[1, '文', [3, 4, 5], 'asd', 666, '999']
>>> case.remove(999)
Traceback (most recent call last):
  File "<pyshell#55>", line 1, in <module>
    case.remove(999)
ValueError: list.remove(x): x not in list

#spilt:可以将字符串拆分成一个列表
>>> "Traceback (most recent call last)".split()
['Traceback', '(most', 'recent', 'call', 'last)']

#sort:将列表元素排序,作用相当于sorted函数,sort、sorted不支持对嵌套列表进行排序
>>> case=[3,5,1,6]
>>> case.sort()
>>> case
[1, 3, 5, 6]
>>> sorted(case)
[1, 3, 5, 6]
>>> case=[1,2,'文',[3,4,5],'asd']
>>> case.sort()
Traceback (most recent call last):
  File "<pyshell#77>", line 1, in <module>
    case.sort()
TypeError: '<' not supported between instances of 'list' and 'str'

#reverse:将列表元素反序显示
>>> case=[1,2,'文',[3,4,5],'asd']
>>> case.reverse()
>>> case
['asd', [3, 4, 5], '文', 2, 1]

对列表的其他操作

>>> case=[1,2,'文',[3,4,5],'asd']
>>> for each in case:
		print(each)	
1
2[3, 4, 5]
asd

#成员检查,判断x是否在列表中
>>> 1 in case
True

列表与元组对比

  • 列表与元组类似:
    • 列表中每个元素类型可以不一样
    • 访问列表中元素时采用索引形式
  • 列表与元组不同:
    • 列表的大小没有限制,类型可以随时修改

猜你喜欢

转载自blog.csdn.net/Sonia_du/article/details/88243967