基础数据类型(二)

  • 列表
  • 列表的增删改查
  • 列表的方法
  • 列表的嵌套
  • 元组
  • range

列表

用来存储大量数据

并且是可变数据类型即可以通过下标去操作的

lst=['hello',1,2,3,'world']
print(lst)

列表的增删改查

#增
# lst=['hello',1,2,3,'world']
# lst.append('高圆圆')#在末尾位置追加
# print(lst)

# lst.insert(-1,'美女')#在-1之前的位置插入
# print(lst)
# lst.insert(1,'蛇')#在1之前插入
# print(lst)

# lst.extend([1,2,3])#迭代添加——并且是在末尾位置
# print(lst)
#删
# lst=['hello',1,2,3,'world']
# del lst#直接删掉lst

# del lst[0]#删掉索引
# print(lst)

# del lst[0:2]#按切片删
# print(lst)

# lst.clear()#清空列表
# print(lst)

# 改
# lst=['hello',1,2,3,'world']
# lst[0]='olleh'#按照索引,去改
# print(lst)

# 按照切片去改***

# lst=['hello',1,2,3,'world']
# lst[0:2]='hh'#是把必须可迭代的数据拆分开,按照索引去改,结果    ['h', 'h', 2, 3, 'world']
# print(lst)
# lst[0:2]=['h','s','h']#如果超过范围,则后边的数据依次往后排 结果['h', 's', 'h', 2, 3, 'world']
# print(lst)
# lst[0:2]=True#整型,布尔值不行会报错
# print(lst)
# lst[0:2]='h'#不够直接0,1索引改成h   结果['h', 2, 3, 'world']
# print(lst)

# lst[0:]='hh'#不够直接覆盖  结果['h', 'h']
# print(lst)

# lst[0:]='hhhhhhhhhhh'#多了直接覆盖前面的,结果['h', 'h', 'h', 'h', 'h', 'h', 'h', 'h', 'h', 'h', 'h']
# print(lst)

# lst=['hello',1,2,3,'world']
# lst[0:3:2]='hh'#按照切片+步长去改,长度必须统一,多或少都会报错
# print(lst)

# 查
# lst=['hello',1,2,3,'world']
# # for i in lst:#利用for循环去查
# #     print(i)
# print(lst[0:])#按照切片去查
# print(lst[0])#按照索引去查

  列表的方法

# lst=['hello',1,2,3,'world']
# print(lst.count(1))#计数器

# lst.reverse()#该方法只是一个操作,没有返回值
# print(lst)

# print(lst.index('hell'))#查看索引,找不到报错
# lst=[1,4,2,3,8]
# lst.sort()#升序
# print(lst)  结果[1, 2, 3, 4, 8]

# lst.sort(reverse=True)
# print(lst)#j降序
#
# lst=['apple','banana','monkey','cmr']
# lst.sort()#按照a,b,c,d顺序
# print(lst)

# lst=['高圆圆','杨字','monksy']
# lst.sort()#汉字的话按照ascill顺序排序
# print(lst)
# lst=['hello',1,2,3,'world']
# lst1=lst.copy()#列表的复制

# print(id(lst))#1777721082312
# print(id(lst1))#1777721050248

  列表的嵌套

lst=['hello',1,2,['world',22,['like']]]
# 取到like
print(lst[-1][-1][0])#按照索引取取值结果:like

lst[0]='ellho'#按照索引取修改值结果:['ellho', 1, 2, ['world', 22, ['like']]]
print(lst)

  元组(只读列表,不可增删改)

用圆括号括起来

# tu=(123)
# tu1=(123,)
# print(type(tu),type(tu1))#<class 'int'> <class 'tuple'>,有无逗号很关键,没有逗号只有一个数据,其数据类型就是其本身

# tu=(True)
# tu1=(True,1)
# print(type(tu),type(tu1))#<class 'bool'> <class 'tuple'>

# tu=('h')
# tu1=('h',)
# tu2=(int(True))
# print(type(tu),type(tu1),type(tu2))#<class 'str'> <class 'tuple'> <class 'int'>

  range

#在python3中
print(range(0,10))#结果   直接打印range(0, 10)
for i in range(0,10):
    print(i)
# 在python2中
1.print(range(0,10))#结果    
# 打印
0
1
2
3
4
5
6
7
8
9
2.python2中print(xrange(0,10))==python3中的print(range(0,10))

  

猜你喜欢

转载自www.cnblogs.com/liuer-mihou/p/10208627.html