python基本資料型別總結

2021-08-09 12:30:00 字數 3219 閱讀 2878

一、列表

列表是有序可以重複的集合,支援增刪改查操作

1.插入:

names = ['老王','老李','老劉']

print(names)

列印的結果為:['老王', '老李', '老劉', '老趙']

2)insert方法可以在指定的下標處插入乙個元素

names = ['老王','老李','老劉','老趙']

names.insert(0,'八戒')

print(names)

列印的結果為:['八戒', '老王', '老李', '老劉', '老趙']
3)+ 操作符可以合併連個列表

names1 = ['老王','老李','老劉','老趙']

names2 = ['八戒','悟空','沙僧','唐僧'];

names3 = names1 + names2

print(names3)

列印的結果為:['老王', '老李', '老劉', '老趙', '八戒', '悟空', '沙僧', '唐僧']
4)extend方法可以把乙個列表合併到另乙個列表裡

names1 = ['老王','老李','老劉','老趙']

names2 = ['八戒','悟空','沙僧','唐僧'];

names1.extend(names2)

print(names1)

列印的結果為:['老王','老李','老劉','老趙','八戒','悟空','沙僧','唐僧']
2.刪除:

1)pop方法刪除列表中的最後乙個元素

names1 = ['老王','老李','老劉','老趙']

names1.pop()

print(names1)

列印的結果為:['老王', '老李', '老劉']
2)remove方法刪除列表中找到的第乙個元素
names1 = ['老王','老李','老劉','老趙','老王']

names1.remove('老王')

print(names1)

列印的結果為:['老李', '老劉', '老趙', '老王']

3)del操作刪除列表中指定下標的元素

names1 = ['老王','老李','老劉','老趙']

del names1[0]

print(names1)

3.修改:

names1 = ['老王','老李','老劉','老趙']

names1[0] = '八戒'

print(names1)

列印的結果為:['八戒', '老李', '老劉', '老趙']

4.查詢:

1) in 判斷乙個元素是否在列表中

names1 = ['老王','老李','老劉','老趙']

if '老王' in names1:

print("老王在列表中")

列印的結果為:老王在列表中
2) not in 判斷乙個元素是否不在列表中

names1 = ['老王','老李','老劉','老趙']

if '八戒' not in names1:

print("八戒不在列表中")

列印的結果為: 八戒不在列表中

二、字典
字典是鍵值對的集合,支援增刪改查操作
1.增
person = {}

person["name"] = 'ywj'

person["***"] = 'male'

person["address"] = 'wuhan'

person["age"] = 20

print(person)

輸出的結果為:
2.刪
person = {}

person["name"] = 'ywj'

person["***"] = 'male'

person["address"] = 'wuhan'

person["age"] = 20

del person['name']

print(person)

輸出的結果為:

3.改

person = {}

person["name"] = 'ywj'

person["***"] = 'male'

person["address"] = 'wuhan'

person["age"] = 20

person['name'] = 'another person'

print(person)

輸出的結果為:
4.查
person = {}

person["name"] = 'ywj'

person["***"] = 'male'

person["address"] = 'wuhan'

person["age"] = 20

print(person['name'])

print(person.get('name'))

輸出的結果為:
ywj

ywj

python基本資料型別總結

總結一下前面學的字串 列表 元組 字典的總結 字串 字串只能讀取,修改後的值也只能輸出一下,要想真正進行操作的話只有將操作後的引數賦值給新的變數,或者進行強轉。這裡的強轉要值得注意的有很多地方,1.jion join方法是以指定字串作為分隔符,將序列中所有的元素合併為乙個新的字串,這個序列包括列表 ...

基本資料型別總結

基本資料型別 型別 型別說明 使用說明 整形integer 標準資料型別,使用前不必定義 實型reall 標準資料型別,使用前不必定義 字元型character 標準資料型別,使用前不必定義 字串型 string 標準資料型別,使用前不必定義 布林型boolean 標準資料型別,使用前不必定義 列舉...

基本資料型別總結

基本資料型別 型別 型別說明 使用說明 整形integer 標準資料型別,使用前不必定義 實型reall 標準資料型別,使用前不必定義 字元型character 標準資料型別,使用前不必定義 字串型 string 標準資料型別,使用前不必定義 布林型boolean 標準資料型別,使用前不必定義 列舉...