Python-list(3)
来源:互联网 发布:淘宝偏远地区有哪些 编辑:程序博客网 时间:2024/06/06 10:38
一、容器之一 list
# 初始化列表li = [1, 2, 3, 'abc', 4.5, [2, 3, 4], {1:'one'}]
注:list 作为容器,可以包容各种其他格式。
1、获取长度
len(li)
2、根据索引读写
print(li[0]) # 首位,0是第一位,最后一位索引为len(li)-1
print(li[3]) # 第四个位置
print(li[-1]) # 利用-1反向获取最后一位
3、添加元素(注意append和extend的区别)
li = [1, 2, 3]
li.append('a') # 将a添加到li末位,输出 [1, 2, 3, 'a']
li.append([4, 5, 6]) # 将整个list添加到li中,输出[1, 2, 3, 'a', [4, 5, 6]]
li = [1, 2, 3]
li.extend([4, 5, 6]) # 将[4, 5, 6] 中的元素逐个添加到li中,输出 [1, 2, 3, 4, 5, 6]
4、删除元素(pop和del)
li = [1, 2, 3, 4, 5]
li.pop() # 从最后一个进行逐个删除,并返回被删除的元素,并修改原list中的内容
del(li[0]) # 将li中删除第一个元素,不返回内容,并修改原list中的内容
5、元素是否存在
li = [1, 2, 3, 4, 5]
print(1 in li) # 判定1是否在li中,返回True或者False
6、列表是否为空
li = []
if not li: # 判断li中是否为空
print('Empty')
else:
print('Not empty')
注:也可以用len(li)来判断
7、字符串(list拆解,join恢复)
s = 'abcdefg'
li = list(s) # 若原s为字符串,则list(s) 将字符串每个元素进行拆解。输出:['a', 'b', 'c', 'd', 'e', 'f', 'g']
li[4] = 'E' # 将第五位的字母替换成E
li[5] = 'F' # 将第六位的字母替换成F
si = '.'.join(li) # 将li中的字母重新恢复成字符串
8、遍历
li = [1, 2, 3]
for i in li: # 直接对元素进行遍历
print(i)
for i in range(len(li)): # 利用索引对元素进行遍历
print(li[i])
- Python-list(3)
- Python(3)--list和tuple
- Python List:
- python list
- python list
- python list
- Python.list
- Python list
- python list
- Python List
- Python List
- python list
- Python---list
- python-list
- python list
- python list
- python list
- Python List
- CSS3--选择器
- nds详解
- 禁用浏览器滚动事件(不隐藏其滚动条)
- Python学习之re模块
- P1428 小鱼比可爱
- Python-list(3)
- 大概是史上最炫酷便捷的扫描仪……
- 扫描线填充算法,单链表实现
- Mac tar.gz方式安装、配置MySQL 5.7.18
- 设计模式C++实现(1)——工厂模式
- 去外包公司的伙伴们小心了!——亲身经历,数数外包公司的坑
- nginx的简单优化和反向代理
- 进程间通信----->共享内存
- 1等于0.循环9吗?