日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python集合加个逗号_8.Python集合与字符串

發布時間:2025/3/21 python 49 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python集合加个逗号_8.Python集合与字符串 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

高級變量類型

目標

列表

元組

字典

字符串

公共方法

變量高級

知識點回顧

Python 中數據類型可以分為 數字型 和 非數字型

數字型

整型 (int)

浮點型(float)

布爾型(bool)

真 True 非 0 數 —— 非零即真

假 False 0

復數型 (complex)

主要用于科學計算,例如:平面場問題、波動問題、電感電容等問題

非數字型

字符串

列表

元組

字典

在 Python 中,所有 非數字型變量 都支持以下特點:

都是一個 序列 sequence,也可以理解為 容器

取值 []

遍歷 for in

計算長度、最大/最小值、比較、刪除

鏈接 + 和 重復 *

切片

01. 列表

1.1 列表的定義

List(列表) 是 Python 中使用 最頻繁 的數據類型,在其他語言中通常叫做 數組

專門用于存儲 一串 信息

列表用 [] 定義,數據 之間使用 , 分隔

列表的 索引 從 0 開始

索引 就是數據在 列表 中的位置編號,索引 又可以被稱為 下標

注意:從列表中取值時,如果 超出索引范圍,程序會報錯

name_list = ["zhangsan", "lisi", "wangwu"]

image

1.2 列表常用操作

在 ipython3 中定義一個 列表,例如:name_list = []

輸入 name_list. 按下 TAB 鍵,ipython 會提示 列表 能夠使用的 方法 如下:

In [1]: name_list.

name_list.append name_list.count name_list.insert name_list.reverse

name_list.clear name_list.extend name_list.pop name_list.sort

name_list.copy name_list.index name_list.remove

序號

分類

關鍵字 / 函數 / 方法

說明

1

增加

列表.insert(索引, 數據)

在指定位置插入數據

列表.append(數據)

在末尾追加數據

列表.extend(列表2)

將列表2 的數據追加到列表

2

修改

列表[索引] = 數據

修改指定索引的數據

3

刪除

del 列表[索引]

刪除指定索引的數據

列表.remove[數據]

刪除第一個出現的指定數據

列表.pop

刪除末尾數據

列表.pop(索引)

刪除指定索引數據

列表.clear

清空列表

4

統計

len(列表)

列表長度

列表.count(數據)

數據在列表中出現的次數

5

排序

列表.sort()

升序排序

列表.sort(reverse=True)

降序排序

列表.reverse()

逆序、反轉

del 關鍵字(科普)

使用 del 關鍵字(delete) 同樣可以刪除列表中元素

del 關鍵字本質上是用來 將一個變量從內存中刪除的

如果使用 del 關鍵字將變量從內存中刪除,后續的代碼就不能再使用這個變量了

del name_list[1]

在日常開發中,要從列表刪除數據,建議 使用列表提供的方法

關鍵字、函數和方法(科普)

關鍵字 是 Python 內置的、具有特殊意義的標識符

In [1]: import keyword

In [2]: print(keyword.kwlist)

In [3]: print(len(keyword.kwlist))

關鍵字后面不需要使用括號

函數 封裝了獨立功能,可以直接調用

函數名(參數)

函數需要死記硬背

方法 和函數類似,同樣是封裝了獨立的功能

方法 需要通過 對象 來調用,表示針對這個 對象 要做的操作

對象.方法名(參數)

在變量后面輸入 .,然后選擇針對這個變量要執行的操作,記憶起來比函數要簡單很多

1.3 循環遍歷

遍歷 就是 從頭到尾 依次 從 列表 中獲取數據

在 循環體內部 針對 每一個元素,執行相同的操作

在 Python 中為了提高列表的遍歷效率,專門提供的 迭代 iteration 遍歷

使用 for 就能夠實現迭代遍歷

# for 循環內部使用的變量 in 列表

for name in name_list:

循環內部針對列表元素進行操作

print(name)

image

1.4 應用場景

盡管 Python 的 列表 中可以 存儲不同類型的數據

但是在開發中,更多的應用場景是

列表 存儲相同類型的數據

通過 迭代遍歷,在循環體內部,針對列表中的每一項元素,執行相同的操作

02. 元組

2.1 元組的定義

Tuple(元組)與列表類似,不同之處在于元組的 元素不能修改

元組 表示多個元素組成的序列

元組 在 Python 開發中,有特定的應用場景

用于存儲 一串 信息,數據 之間使用 , 分隔

元組用 () 定義

元組的 索引 從 0 開始

索引 就是數據在 元組 中的位置編號

info_tuple = ("zhangsan", 18, 1.75)

創建空元組

info_tuple = ()

元組中 只包含一個元素 時,需要 在元素后面添加逗號

info_tuple = (50, )

image

2.2 元組常用操作

在 ipython3 中定義一個 元組,例如:info = ()

輸入 info. 按下 TAB 鍵,ipython 會提示 元組 能夠使用的函數如下:

info.count info.index

有關 元組 的 常用操作 可以參照上圖練習

2.3 循環遍歷

取值 就是從 元組 中獲取存儲在指定位置的數據

遍歷 就是 從頭到尾 依次 從 元組 中獲取數據

# for 循環內部使用的變量 in 元組

for item in info:

循環內部針對元組元素進行操作

print(item)

在 Python 中,可以使用 for 循環遍歷所有非數字型類型的變量:列表、元組、字典 以及 字符串

提示:在實際開發中,除非 能夠確認元組中的數據類型,否則針對元組的循環遍歷需求并不是很多

2.4 應用場景

盡管可以使用 for in 遍歷 元組

但是在開發中,更多的應用場景是:

函數的 參數 和 返回值,一個函數可以接收 任意多個參數,或者 一次返回多個數據

有關 函數的參數 和 返回值,在后續 函數高級 給大家介紹

格式字符串,格式化字符串后面的 () 本質上就是一個元組

讓列表不可以被修改,以保護數據安全

info = ("zhangsan", 18)

print("%s 的年齡是 %d" % info)

元組和列表之間的轉換

使用 list 函數可以把元組轉換成列表

list(元組)

使用 tuple 函數可以把列表轉換成元組

tuple(列表)

03. 字典

3.1 字典的定義

dictionary(字典) 是 除列表以外 Python 之中 最靈活 的數據類型

字典同樣可以用來 存儲多個數據

通常用于存儲 描述一個 物體 的相關信息

和列表的區別

列表 是 有序 的對象集合

字典 是 無序 的對象集合

字典用 {} 定義

字典使用 鍵值對 存儲數據,鍵值對之間使用 , 分隔

鍵 key 是索引

值 value 是數據

鍵 和 值 之間使用 : 分隔

鍵必須是唯一的

值 可以取任何數據類型,但 鍵 只能使用 字符串、數字或 元組

xiaoming = {"name": "小明",

"age": 18,

"gender": True,

"height": 1.75}

image

3.2 字典常用操作

2、查詢

由于字典是無序的,故要獲取字典的值,必須通過key來獲取;

####### a、字典[key]——》獲取key值對應的值

注意:key值必須是存在的,否則會報KeyError

student={'name':'alice','age':12,'sex':'boy'}

print(student['name']) #alice

print(student['sex']) #boy

print(student['score']) #KeyError: 'score'

b、字典.get(key)——>通過key獲取值

注意:key值不存在的不會報錯,結果是none

某個key值肯定存在的時候用a型,key值可能不存在的時候用b型;

print(student.get('score')) #None

c、直接遍歷字典(推薦使用)

通過for-in遍歷字典拿到的是key值

for x in student:

print(student[x])

d、其他遍歷字典

3、增(增加鍵值對)

語法:字典[key]=值 key必須是在字典中不存在的

student['score']=98

print(student) #{'name': 'alice', 'age': 12, 'sex': 'boy', 'score': 98}

4、改(修改值,非key)

語法: 字典[key]=值 key必須是在字典中存在的

student['name']='harry'

print(student) #{'name': 'harry', 'age': 12, 'sex': 'boy', 'score': 98}

5、刪(刪除鍵值對)

a、語法: del 字典[key] 刪除字典中某個鍵值對

del student['sex']

print(student) #{'name': 'harry', 'age': 12, 'score': 98}

b、語法: 字典.pop(key) 實質是從字典中取走某個鍵值對,非刪除

new_age=student.pop('age')

print(student,new_age) #{'name': 'harry', 'score': 98} 12 age鍵值對從字典中已取走,但還存在,故能獲取

(二)字典相關操作

1、字典相關運算

== 判斷兩個字典的值是否相等

is 判斷兩個字典的地址是否相等

in 和 not in 判斷字典中是否包含某個鍵值(key),非值(value)

dic1 = {'a': 1, 'b': 2}

aa = dic1

print(dic1 is aa) #True

print({'a': 100, 'b': 200} == {'b': 200, 'a': 100}) #True

print({'a': 100, 'b': 200} is {'b': 200, 'a': 100}) #False

print('abc' in {'abc': 100, 'a': 200}) # True

print('abc' in {'100': 'abc', 'a': 200}) # False

(三)字典的函數和方法

1、 len(字典)--> 獲取鍵值對的個數

dict1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4}

print(len(dict1))#4

2、字典.clear()--> 清空字典

dict1.clear()

print(dict1)#{}

3、字典.copy()--> 將字典中的鍵值對復制一份產生一個新的字典

dict1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4}

dict2 = dict1.copy()

print(dict2, dict1 is dict2)#{'a': 1, 'b': 2, 'c': 3, 'd': 4} False

####### 值相同,地址不同

4、dict.fromkeys(序列,值)--> 創建一個字典,將序列中的每個元素作為key,值作為value

Python 字典 fromkeys() 函數用于創建一個新字典,以序列seq中元素做字典的鍵,值value為字典所有鍵對應的初始值。

dict3 = dict.fromkeys('xyz', 100)

print(dict3)#{'x': 100, 'y': 100, 'z': 100}

dict3 = dict.fromkeys(['aa', 'bb', 'cc'], (1, 2))

print(dict3)#{'aa': (1, 2), 'bb': (1, 2), 'cc': (1, 2)}

5、get方法

字典.get(key)

字典.get(key,默認值)

返回指定鍵key的值,如果值不在字典中則返回None

student = {}

student.get('name','xm') #字典.get()是訪問、獲取、查詢某個鍵,而非創建

print(student,type(student)) #{}

print(student.get('name','xm'))#xm 字典.get()是訪問、獲取、查詢某個鍵,返回指定鍵key的值

student.setdefault('sex','boy')#字典.setdefault()是創建新鍵

print(student,type(student)) #{'sex': 'boy'}

print(student.get('name'))#None

print(student.get('name', '無名'))#無名

6、key、value、items方法

字典.keys() -->返回所有鍵對應的序列

字典.values()-->返回所有值對應的序列

字典.items()-->將每個鍵值對轉換成元祖,作為一個序列的元素

注意:返回的都不是列表,是其他類型的序列

dict1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4}

print(dict1.keys(),dict1.values(),sep='====')#dict_keys(['a', 'b', 'c', 'd'])====dict_values([1, 2, 3, 4])

items = list(dict1.items())

print(items, type(items)) #[('a', 1), ('b', 2), ('c', 3), ('d', 4)]

print(dict1.items(), type(dict1.items())) #dict_items([('a', 1), ('b', 2), ('c', 3), ('d', 4)])

7、setdefault方法

字典.setdefault(key)

字典.setdefault(key,value)

和get()類似, 如果鍵不存在于字典中,將會添加鍵key并將值設為None或者value;

如果鍵存在,不會對字典進行任何操作(key和value均不改變);

注意:語法-字典.get()是訪問字典某鍵,語法-字典.setdefault()是創建某鍵;

dict1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4}

dict1.setdefault('aa')

print(dict1)#{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'aa': None}

8、update方法

字典1.update(字典2)——》把字典2的鍵值對更新到字典1里,不存在的鍵值對則進行添加;

dict1 = {'a': 1, 'b': 2}

dict2 = {'b': 200, 'c': 100}

dict1.update(dict2)

print(dict1) #{'a': 1, 'b': 200, 'c': 100}

04. 字符串

4.1 字符串的定義

字符串 就是 一串字符,是編程語言中表示文本的數據類型

在 Python 中可以使用 一對雙引號 " 或者 一對單引號 ' 定義一個字符串

雖然可以使用 \" 或者 \' 做字符串的轉義,但是在實際開發中:

如果字符串內部需要使用 ",可以使用 ' 定義字符串

如果字符串內部需要使用 ',可以使用 " 定義字符串

可以使用 索引 獲取一個字符串中 指定位置的字符,索引計數從 0 開始

也可以使用 for 循環遍歷 字符串中每一個字符

大多數編程語言都是用 " 來定義字符串

string = "Hello Python"

for c in string:

print(c)

image

4.2 字符串的常用操作

在 ipython3 中定義一個 字符串,例如:hello_str = ""

輸入 hello_str. 按下 TAB 鍵,ipython 會提示 字符串 能夠使用的 方法 如下:

In [1]: hello_str.

hello_str.capitalize hello_str.isidentifier hello_str.rindex

hello_str.casefold hello_str.islower hello_str.rjust

hello_str.center hello_str.isnumeric hello_str.rpartition

hello_str.count hello_str.isprintable hello_str.rsplit

hello_str.encode hello_str.isspace hello_str.rstrip

hello_str.endswith hello_str.istitle hello_str.split

hello_str.expandtabs hello_str.isupper hello_str.splitlines

hello_str.find hello_str.join hello_str.startswith

hello_str.format hello_str.ljust hello_str.strip

hello_str.format_map hello_str.lower hello_str.swapcase

hello_str.index hello_str.lstrip hello_str.title

hello_str.isalnum hello_str.maketrans hello_str.translate

hello_str.isalpha hello_str.partition hello_str.upper

hello_str.isdecimal hello_str.replace hello_str.zfill

hello_str.isdigit hello_str.rfind

提示:正是因為 python 內置提供的方法足夠多,才使得在開發時,能夠針對字符串進行更加靈活的操作!應對更多的開發需求!

1) 判斷類型 - 9

方法

說明

string.isspace()

如果 string 中只包含空格,則返回 True

string.isalnum()

如果 string 至少有一個字符并且所有字符都是字母或數字則返回 True

string.isalpha()

如果 string 至少有一個字符并且所有字符都是字母則返回 True

string.isdecimal()

如果 string 只包含數字則返回 True,全角數字

string.isdigit()

如果 string 只包含數字則返回 True,全角數字、⑴、\u00b2

string.isnumeric()

如果 string 只包含數字則返回 True,全角數字,漢字數字

string.istitle()

如果 string 是標題化的(每個單詞的首字母大寫)則返回 True

string.islower()

如果 string 中包含至少一個區分大小寫的字符,并且所有這些(區分大小寫的)字符都是小寫,則返回 True

string.isupper()

如果 string 中包含至少一個區分大小寫的字符,并且所有這些(區分大小寫的)字符都是大寫,則返回 True

2) 查找和替換 - 7

方法

說明

string.startswith(str)

檢查字符串是否是以 str 開頭,是則返回 True

string.endswith(str)

檢查字符串是否是以 str 結束,是則返回 True

string.find(str, start=0, end=len(string))

檢測 str 是否包含在 string 中,如果 start 和 end 指定范圍,則檢查是否包含在指定范圍內,如果是返回開始的索引值,否則返回 -1

string.rfind(str, start=0, end=len(string))

類似于 find(),不過是從右邊開始查找

string.index(str, start=0, end=len(string))

跟 find() 方法類似,不過如果 str 不在 string 會報錯

string.rindex(str, start=0, end=len(string))

類似于 index(),不過是從右邊開始

string.replace(old_str, new_str, num=string.count(old))

把 string 中的 old_str 替換成 new_str,如果 num 指定,則替換不超過 num 次

3) 大小寫轉換 - 5

方法

說明

string.capitalize()

把字符串的第一個字符大寫

string.title()

把字符串的每個單詞首字母大寫

string.lower()

轉換 string 中所有大寫字符為小寫

string.upper()

轉換 string 中的小寫字母為大寫

string.swapcase()

翻轉 string 中的大小寫

4) 文本對齊 - 3

方法

說明

string.ljust(width)

返回一個原字符串左對齊,并使用空格填充至長度 width 的新字符串

string.rjust(width)

返回一個原字符串右對齊,并使用空格填充至長度 width 的新字符串

string.center(width)

返回一個原字符串居中,并使用空格填充至長度 width 的新字符串

5) 去除空白字符 - 3

方法

說明

string.lstrip()

截掉 string 左邊(開始)的空白字符

string.rstrip()

截掉 string 右邊(末尾)的空白字符

string.strip()

截掉 string 左右兩邊的空白字符

6) 拆分和連接 - 5

方法

說明

string.partition(str)

把字符串 string 分成一個 3 元素的元組 (str前面, str, str后面)

string.rpartition(str)

類似于 partition() 方法,不過是從右邊開始查找

string.split(str="", num)

以 str 為分隔符拆分 string,如果 num 有指定值,則僅分隔 num + 1 個子字符串,str 默認包含 '\r', '\t', '\n' 和空格

string.splitlines()

按照行('\r', '\n', '\r\n')分隔,返回一個包含各行作為元素的列表

string.join(seq)

以 string 作為分隔符,將 seq 中所有的元素(的字符串表示)合并為一個新的字符串

4.3 字符串的切片

切片 方法適用于 字符串、列表、元組

切片 使用 索引值 來限定范圍,從一個大的 字符串 中 切出 小的 字符串

列表 和 元組 都是 有序 的集合,都能夠 通過索引值 獲取到對應的數據

字典 是一個 無序 的集合,是使用 鍵值對 保存數據

image

字符串[開始索引:結束索引:步長]

注意:

指定的區間屬于 左閉右開 型 [開始索引, 結束索引) => 開始索引 >= 范圍 < 結束索引

從 起始 位開始,到 結束位的前一位 結束(不包含結束位本身)

從頭開始,開始索引 數字可以省略,冒號不能省略

到末尾結束,結束索引 數字可以省略,冒號不能省略

步長默認為 1,如果連續切片,數字和冒號都可以省略

索引的順序和倒序

在 Python 中不僅支持 順序索引,同時還支持 倒序索引

所謂倒序索引就是 從右向左 計算索引

最右邊的索引值是 -1,依次遞減

演練需求

截取從 2 ~ 5 位置 的字符串

截取從 2 ~ 末尾 的字符串

截取從 開始 ~ 5 位置 的字符串

截取完整的字符串

從開始位置,每隔一個字符截取字符串

從索引 1 開始,每隔一個取一個

截取從 2 ~ 末尾 - 1 的字符串

截取字符串末尾兩個字符

字符串的逆序(面試題)

答案

num_str = "0123456789"

# 1\. 截取從 2 ~ 5 位置 的字符串

print(num_str[2:6])

# 2\. 截取從 2 ~ `末尾` 的字符串

print(num_str[2:])

# 3\. 截取從 `開始` ~ 5 位置 的字符串

print(num_str[:6])

# 4\. 截取完整的字符串

print(num_str[:])

# 5\. 從開始位置,每隔一個字符截取字符串

print(num_str[::2])

# 6\. 從索引 1 開始,每隔一個取一個

print(num_str[1::2])

# 倒序切片

# -1 表示倒數第一個字符

print(num_str[-1])

# 7\. 截取從 2 ~ `末尾 - 1` 的字符串

print(num_str[2:-1])

# 8\. 截取字符串末尾兩個字符

print(num_str[-2:])

# 9\. 字符串的逆序(面試題)

print(num_str[::-1])

05. 公共方法

5.1 Python 內置函數

Python 包含了以下內置函數:

函數

描述

備注

len(item)

計算容器中元素個數

del(item)

刪除變量

del 有兩種方式

max(item)

返回容器中元素最大值

如果是字典,只針對 key 比較

min(item)

返回容器中元素最小值

如果是字典,只針對 key 比較

cmp(item1, item2)

比較兩個值,-1 小于/0 相等/1 大于

Python 3.x 取消了 cmp 函數

注意

字符串 比較符合以下規則: "0" < "A" < "a"

5.2 切片

| 描述 | Python 表達式 | 結果 | 支持的數據類型 |

| :---: | --- | --- | --- | --- |

| 切片 | "0123456789"[::-2] | "97531" | 字符串、列表、元組 |

切片 使用 索引值 來限定范圍,從一個大的 字符串 中 切出 小的 字符串

列表 和 元組 都是 有序 的集合,都能夠 通過索引值 獲取到對應的數據

字典 是一個 無序 的集合,是使用 鍵值對 保存數據

5.3 運算符

運算符

Python 表達式

結果

描述

支持的數據類型

+

[1, 2] + [3, 4]

[1, 2, 3, 4]

合并

字符串、列表、元組

*

["Hi!"] * 4

['Hi!', 'Hi!', 'Hi!', 'Hi!']

重復

字符串、列表、元組

in

3 in (1, 2, 3)

True

元素是否存在

字符串、列表、元組、字典

not in

4 not in (1, 2, 3)

True

元素是否不存在

字符串、列表、元組、字典

> >= == < <=

(1, 2, 3) < (2, 2, 3)

True

元素比較

字符串、列表、元組

注意

in 在對 字典 操作時,判斷的是 字典的鍵

in 和 not in 被稱為 成員運算符

成員運算符

成員運算符用于 測試 序列中是否包含指定的 成員

運算符

描述

實例

in

如果在指定的序列中找到值返回 True,否則返回 False

3 in (1, 2, 3) 返回 True

not in

如果在指定的序列中沒有找到值返回 True,否則返回 False

3 not in (1, 2, 3) 返回 False

注意:在對 字典 操作時,判斷的是 字典的鍵

5.4 完整的 for 循環語法

在 Python 中完整的 for 循環 的語法如下:

for 變量 in 集合:

循環體代碼

else:

沒有通過 break 退出循環,循環結束后,會執行的代碼

應用場景

在 迭代遍歷 嵌套的數據類型時,例如 一個列表包含了多個字典

需求:要判斷 某一個字典中 是否存在 指定的 值

如果 存在,提示并且退出循環

如果 不存在,在 循環整體結束 后,希望 得到一個統一的提示

students = [

{"name": "阿土",

"age": 20,

"gender": True,

"height": 1.7,

"weight": 75.0},

{"name": "小美",

"age": 19,

"gender": False,

"height": 1.6,

"weight": 45.0},

]

find_name = "阿土"

for stu_dict in students:

print(stu_dict)

# 判斷當前遍歷的字典中姓名是否為find_name

if stu_dict["name"] == find_name:

print("找到了")

# 如果已經找到,直接退出循環,就不需要再對后續的數據進行比較

break

else:

print("沒有找到")

print("循環結束")

總結

以上是生活随笔為你收集整理的python集合加个逗号_8.Python集合与字符串的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。