1. 程式人生 > >基礎資料型別(二)

基礎資料型別(二)

  • 列表
  • 列表的增刪改查
  • 列表的方法
  • 列表的巢狀
  • 元組
  • 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))