Python——浅谈关于列表的使用方法

在Python中有六种内建的序列:列表、元组、字符串、Unicode字符串、buffer对象和xrange对象。在这里只讨论关于Python中列表的定义:

在Python中没有所谓数组的概念,但是在Python中列表与数组很相像。列表的数据项不需要具有相同的数据类型。列表中的每个元素都分配一个数字 -即它的位置,第一个数据类型在列表中的位置是0,第二个数据类型在列表中的位置是1,依此类推。

1. 创建一个列表:

>>> list1 = ['hello','world']
>>> list2 = ['Any',123]

>>> list3 = [123,456]

2. 列表大致有四种操作,分别为增、减、修、排

增:

  1.使用append,默认将所添加的内容排到列表的最后一项

数组名.append(添加的内容)

 >>> list1.append('Any')
>>> list1
['hello', 'world', 'Any']

   2.使用insert,可以将所要添加的内容添加到列表的任意一项内容之后

数组名.insert(任意一项的下标加1,添加的内容)

>>> list2.insert(1,'girl')
>>> list2
['Any', 'girl', 123]

3. 使用extend,默认将所添加的内容排到列表的最后一项

>>> list3.extend('hello')
>>> list3
[123, 456, 'h', 'e', 'l', 'l', 'o']

 修

1.通过知道所要修改内容的下标,而对内容进行一个一个修改

>>> list4 = ['hello','Any']
>>> list4[1] = 'world'
>>> list4
['hello', 'world']

 2.所要修改的内容在一块,而且大于1个以上

>>> list5 = ['Any','gril',26,'music']
>>> list5[1:3] = ['boy',43]
>>> list5
['Any', 'boy', 43, 'music']

排:

1.使用sort,对数据按照其在ASCII中所排的位置进行排序

>>> list2=[121,120,3525,90834]
>>> list2.sort()
>>> list2
[120, 121, 3525, 90834]

 >>> list1 = ['sadj','assge','asaue']
>>> list1.sort()
>>> list1
['asaue', 'assge', 'sadj']

而在使用sort时,列表中不能出现两种不同的数据类型 

>>> list1 = ['any',23,'hello']
>>> list1.sort()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: '<' not supported between instances of 'int' and 'str' 

 2.使用reverse,对数据按照其在ASCII中所排的位置进行排序

>>> list1 = [12,9,926]
>>> list1.reverse()
>>> list1
[926, 9, 12]

 >>> list2 = ['any','Gril','python']
>>> list2.reverse()
>>> list2
['python', 'Gril', 'any']

如果列表里含有两种不同的数据类型,则会报错 

 >>> list3 = ['any',123,'ash']
>>> list.reverse()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: descriptor 'reverse' of 'list' object needs an argument

 删:

1.使用remove,可对列表中的任意元素进行删除

>>> list1 = ['Any',23,'boy']

>>> list1.remove(23)
>>> list1
['Any', 'boy']

 2.使用pop,对列表中的元素进行删除,所删除的元素会返还给你,但是删除前必须知道所要删除的元素在列表中的位置

>>> list2 = ['hello','Any','boy']

>>> list2.pop(2)
'boy'
>>> list2
['hello', 'Any']

 3.使用clear,对列表中的元素进行全部删除

 >>> list3 = ['Python','hello','book']

 >>> list3.clear()
>>> list3
[]

 4.使用del,可对列表中的元素进行单个删除,也可对列表中的元素进行全部删除

>>> list3 = [1342,7286,'ajakjd']
>>> del list3[2]
>>> list3
[1342, 7286]
>>> del list3
>>> list3
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'list3' is not defined

 

 

 

 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Xa_L

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值