Python入门之列表

Python中的列表类似于C语言中的数组,下面通过实例说明介绍几种常用的使用方法。

1.空列表的创建

>>> empty=[]
>>> print(empty)
[]

2.列表中元素的查看

>>> words=["a","b","c"]
>>> print(words[2])
c
>>> print(words[3])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

3.列表的修改

>>> words=["a",'b',1,2,'3']
>>> words[0]=0
>>> print(words)
[0, 'b', 1, 2, '3']

4.列表的运算

>>> nums=[1,2,3,4,5]
>>> print(nums+[6,7])
[1, 2, 3, 4, 5, 6, 7]
>>> print(nums-[1])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for -: 'list' and 'list'
>>> print(nums*2)
[1, 2, 3, 4, 5, 1, 2, 3, 4, 5]
>>> print(nums/2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for /: 'list' and 'int'

只能进行加乘,且不会改变原列表中的元素。

5.多列表的组合

>>> words=[1,2,3,[4,'a','b'],5,6]
>>> print(words[1])
2
>>> print(words[3][1])
a

6.列表的检测

>>> words=[1,2,3,[4,'a','b'],5,6]
>>> print('c'in words)
False
>>> print('d' not in words)
True
>>> print(not 'd' in words)
True

主要用于检测某元素是否在该列表中

7.列表中元素的插入

>>> nums=[1,2,3,4,5]
>>> nums.append(0)
>>> print(nums)
[1, 2, 3, 4, 5, 0]
>>> index=4
>>> nums.insert(index,"a")
>>> print(nums)
[1, 2, 3, 4, 'a', 5, 0]

append只能插入列表的尾部,而insert可以插入列表的任何位置

8.列表中某元素的位置

>>> words=['p','y','t','h','o','n']
>>> print(words.index('t'))
2

其他函数我就不一一举例,如下:

len(list):获取列表的长度
max(list):获取列表中的最大值
min(list):获取列表中的最小值
list.remove(x):删除列表中的某个元素
list.count(x):获取列表中某元素出现的次数

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值