Python基础-使用list和tuple
2018-03-05 11:12
711 查看
1.list
Python内置的一种数据类型是列表:list。list是一种有序的集合,可以随时删除和添加元素#student的集合studentsstudents = ['周建','周围','周瑜']
print(students)
#取集合中的第一个元素
#print(students[0])
print(students[-3])
#取集合中的第二个元素
#print(students[1])
print(students[-2])
#取集合中的第三个元素
#print(students[2])
print(students[-1])
#打印出集合的长度
print(len(students))
打印结果:['周建', '周围', '周瑜']
周建
周围
周瑜
3
#添加元素 students.append('周杰') print(students) #把元素插入到指定位置 students.insert(1,'周杰伦') print(students) #删除集合末尾的元素 students.pop() print(students) #删除指定位置的元素 students.pop(1) print(students) #把某个元素替换成别的元素 students[1] = '周润发' print(students)
打印结果:['周建', '周围', '周瑜', '周杰']
['周建', '周杰伦', '周围', '周瑜', '周杰']
['周建', '周杰伦', '周围', '周瑜']
['周建', '周围', '周瑜']
['周建', '周润发', '周瑜']
#list元素的数据类型可以不同 lists = ['周建',45,True] print(lists)
打印结果:['周建', 45, True]
#list元素也可以是另一个list s = ['Python',['Android','iOS'],'Java'] print(s) print(len(s))
打印结果:['Python', ['Android', 'iOS'], 'Java'] 3
2.tuple
另一种有序列表叫元组:tuple,tuple和list相似,tuple一旦初始化就不能改变,它也没有append()、insert()方法因为tuple不可变,所以代码更加安全
a = ('a','b','c')
print(a)
b = ('a','b',['A','B'])
print(b[2][0])
print(b[2][1])
打印结果:
('a', 'b', 'c')
A
B
相关文章推荐
- Python基础3——使用list和tuple
- python学习(3)python基础、使用list和tuple
- python基础——使用list和tuple
- Python基础--使用list和tuple
- python基础学习之——使用list和tuple
- 廖雪峰python3.6教程笔记3-Python基础之使用list, tuple, dict和set
- 【Python】基础学习——列表(list),元祖(tuple),字典(dict),字符串(string),集合(set)
- python基础31[list+tuple+set+dict+str+file的成员方法]
- python基础学习二 list和tuple(列表和元组)
- 【Python】 [基础] list和tuple
- Python语言基础(四)_list与tuple
- Python3 基础:list和tuple
- python学习——使用list和tuple
- Python3基础 list 使用for循环 删除列表中的重复项
- python学习笔记使用list和tuple
- python基础[list,tuple,dictionary,set]
- Python基础教程(六):list、tuple、dictionary
- Python学习笔记—使用list和tuple
- Python3学习(一)-基础、数据类型、变量、字符串和编码、list&tuple、if、for、while、dict、set、函数与参数
- python基础之 list和 tuple(元组)