首页
/
每日頭條
/
科技
/
數據類型分幾種
數據類型分幾種
更新时间:2024-05-03 22:42:06
  • 1 數值型1.1 數值類型的創建1.2 數值類型轉換1.3 python内置的數學相關函數
  • 2 布爾型
  • 3 字符型string
  • 4 列表(list)
  • 5 元組(tuple)
  • 6 字典(dict)
  • 7 集合(set)
  • 作業

計算機是可以做數學計算的機器,因此,計算機程序理所當然地可以處理各種數值。但是,計算機能處理的遠不止數值,還可以處理文本、圖形、音頻、視頻、網頁等各種各樣的數據,不同的數據,需要定義不同的數據類型。在Python中,能夠直接處理的數據類型有以下幾種

1 數值型

數值型分為以下兩種類型:

  • 整型整型長整型(2**62)
  • 浮點型
  • 複數

2 是一個整數的例子。長整數 不過是大一些的整數。3.23和52.3E-4是浮點數的例子。E标記表示10的幂。在這裡,52.3E-4表示52.3 ** 10-4。(-5 4j)和(2.3-4.6j)是複數的例子,其中-5,4為實數,j為虛數,數學中表示複數是什麼?。

3.x已不區分整型與長整型,統統稱為整型

1.1 數值類型的創建

In [1]: a = 10In [2]: b = aIn [3]: b = 666In [4]: print(a)10In [5]: print(b)666

數據類型分幾種(數據類型)1

1.2 數值類型轉換

In [1]: a = '3.14'In [2]: b = '100'

In [3]: type(a)

Out[3]: strIn [4]: type(b)

Out[4]: str

In [5]: c = float(a)In [6]: d = int(b)

In [7]: type(c)

Out[7]: floatIn [8]: type(d)

Out[8]: int

1.3 python内置的數學相關函數

函數名

描述

abs(x)

返回數字的絕對值,如abs(-10)結果返回10

ceil(x)

返回數字的上入整數,如math.ceil(4.1)結果返回5

fabs(x)

返回數字的絕對值,如math.fabs(-10)結果返回10.0

floor(x)

返回數字的下舍整數,如math.floor(4.9)結果返回4

max(x1,x2,…)

返回給定參數的最大值,參數可為序列類型

min(x1,x2,…)

返回給定參數的最小值,參數可為序列類型

pow(x,y)

計算x的y次幂,結果為x ** y運算後的值

round(x [,n])

返回浮點數x的四舍五入值,若給定n值,則代表保留n位小數

2 布爾型

布爾型隻有兩個值:

  • True
  • False

也可用1表示True,用0表示False,請注意首字母大寫

In [1]: TrueOut[1]: True

In [2]: 4 > 2Out[2]: True

In [3]: bool([3,4])Out[3]: True

In [4]: bool([])Out[4]: False

In [5]: True 1Out[5]: 2

與或非操作:

In [7]: bool(1 and 0)

Out[7]: False

In [8]: bool(1 and 1)

Out[8]: True

In [9]: bool(1 or 0)

Out[9]: True

In [10]: bool(not 0)

Out[10]: True

布爾型經常用在條件判斷中:

age=18if age>18: # bool(age>18)

print('old')else:

print('young')

3 字符型string

字符串是以單引号'或雙引号"或三引号'''括起來的任意文本,比如'abc',"123",'''456'''等等。

單引号與雙引号的區别?

請注意,''或""本身隻是一種表示方式,不是字符串的一部分,因此,字符串'abc'隻有a,b,c這3個字符。如果'本身也是一個字符,那就可以用""括起來,比如"I'm OK"包含的字符是I,',m,空格,O,K這6個字符

創建字符串

a = 'Hello world!'

b = "Hello tom"

c = '''hehe'''

字符串相關操作:

# 1 * 重複輸出字符串In [18]: 'hello' * 2

Out[18]: 'hellohello'

# 2 [] ,[:] 通過索引獲取字符串中字符,這裡和列表的切片操作是相同的,具體内容見列表In [19]: 'helloworld'[2:]

Out[19]: 'lloworld'

# 3 in 成員運算符 - 如果字符串中包含給定的字符返回 TrueIn [20]: 'el' in 'hello'

Out[20]: True

# 4 % 格式字符串In [21]: name = 'wangqing'

In [22]: print('wangqing is a good teacher')

wangqing is a good teacher

In [23]: print('%s is a good teacher' % name)

wangqing is a good teacher

萬惡的字符串拼接:python中的字符串在C語言中體現為是一個字符數組,每次創建字符串時候需要在内存中開辟一塊連續的空,并且一旦需要修改字符串的話,就需要再次開辟空間,萬惡的 号每出現一次就會在内從中重新開辟一塊空間。

# 5 字符串拼接In [11]: a='123'In [12]: b='abc'In [13]: c='789'

In [14]: d1=a b cIn [15]: print(d1)123abc789

# 效率低,該用joinIn [16]: d2=''.join([a,b,c])

In [17]: print(d2)123abc789

python内置的字符串相關函數方法:統計次數返回 str 在 string 裡面出現的次數,如果 beg 或者 end 指定則返回指定範圍内 str 出現的次數string.count(str, beg=0, end=len(string))

In [1]: a = 'hello world'

In [2]: a.count('l')

Out[2]: 3

In [3]: a.count('l',3)

Out[3]: 2

首字母大寫

In [1]: a = 'hello world'

In [2]: a.capitalize()

Out[2]: 'Hello world'

内容居中string.center(width) 返回一個原字符串居中,并使用空格填充至長度 width 的新字符串

In [1]: a = 'hello world'

In [2]: a.center(50)

Out[2]: ' hello world '

In [3]: a.center(50,'-')

Out[3]: '-------------------hello world--------------------'

内容左對齊string.ljust(width) 返回一個原字符串左對齊,并使用空格填充至長度 width 的新字符串

In [1]: a = 'hello world'

In [2]: a.ljust(50)

Out[2]: 'hello world '

In [3]: a.ljust(50,'*')

Out[3]: 'hello world***************************************'

内容右對齊string.rjust(width) 返回一個原字符串右對齊,并使用空格填充至長度 width 的新字符串

a = 'hello world'

a.rjust(50) # ' hello world'

a.rjust(50,'*') # '***************************************hello world'

以指定内容結束string.endswith(obj, beg=0, end=len(string)) 檢查字符串是否以 obj 結束,如果beg 或者 end 指定則檢查指定的範圍内是否以 obj 結束,如果是,返回 True,否則返回 False.

a = 'hello world'

a.endswith('d') # True

a.endswith('o',0,5) # True

以指定内容開頭string.startswith(obj, beg=0,end=len(string)) 檢查字符串是否是以 obj 開頭,是則返回 True,否則返回 False。如果beg 和 end 指定值,則在指定範圍内檢查

a = 'hello world'

a.startswith('h') # True

a.startswith('w',5) # False

通過制表符(\t)設置字符間的間隔string.expandtabs(tabsize=8) 把字符串 string 中的 tab 符号轉為空格,tab 符号默認的空格數是 8

a = 'hello\tworld'

a.expandtabs(tabsize=8)

a.expandtabs(tabsize=10)

查找到第一個指定元素的位置,返回其索引值string.find(str, beg=0, end=len(string)) 檢測 str 是否包含在 string 中,如果 beg 和 end 指定範圍,則檢查是否包含在指定範圍内,如果是,返回開始的索引值,否則返回-1

a = 'hello world'

a.find('w') # 6

a.find('p') # -1

從右往左查找到第一個指定元素的位置,返回其索引值從右往左找第一個指定元素的位置,返回其索引值,該索引值的位置是從左到右數的string.rfind(str, beg=0,end=len(string)) 類似于 find()函數,不過是從右邊開始查找

a = 'hello world'

a.rfind('w') # 6 雖然是從右往左找,但是順序是從左數到右的

a.rfind('p') # -1

b = 'hello worldworld'

b.rfind('w') # 11 雖然是從右往左找,但是順序是從左數到右的

查找到第一個指定元素的位置,返回其索引值string.index(str, beg=0, end=len(string)) 跟find()方法一樣,隻不過如果str不在 string中會報一個異常

a = 'hello world'

a.index('w') # 6

a.index('p') # ValueError: substring not found

從右往左查找到第一個指定元素的位置,返回其索引值string.rindex(str,beg=0,end=len(string)) 類似于 index(),不過是從右邊開始

a = 'hello world'

a.rindex('w') # 6

a.rindex('p') # ValueError: substring not found

b = 'hello worldworld'

b.rindex('w') # 11

format格式化字符串将format方法中指定的變量的值替換到字符串中

a = 'My name is {name},I am {age} years old.'

a.format(name='tom',age=20) # 'My name is tom,I am 20 years old.'

format_map格式化字符串将format_map方法中指定的變量的值替換到字符串中

a = 'My name is {name},I am {age} years old.'

a.format_map({'name': 'tom','age': 20}) # 'My name is tom,I am 20 years old.'

判斷字符串中是否全為數字string.isnumeric() 如果 string 中隻包含數字字符,則返回 True,否則返回 False

a = 'abc12cde'

a.isnumeric() # False

b = '123'

b.isnumeric() # True

判斷字符串中是否全為字母string.isalpha() 如果 string 至少有一個字符并且所有字符都是字母則返回 True,否則返回 False

a = 'abc12cde'

a.isalpha() # False

b = 'abcdef'

b.isalpha() # True

判斷是否隻包含字母或數字

a = 'abc12cde'

a.isalnum() # True

b = '123'

b.isalnum() # True

c = 'abc123!@#'

c.isalnum() # False

判斷是否為十進制string.isdecimal() 如果 string 隻包含十進制數字則返回 True 否則返回 False

a = '1234'

a.isdecimal() # True

判斷是否為整數string.isdigit() 如果 string 隻包含數字則返回 True 否則返回 False

a = '1234'

a.isdigit() # True

b = '10.4'

b.isdigit() # False

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

a = 'abcDEF'

a.islower() # False

b = 'abc'

b.islower() # True

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

a = 'abcDEF'

a.isupper() # False

b = 'ABC'

b.isupper() # True

判斷是否為空格string.isspace() 如果 string 中隻包含空格,則返回 True,否則返回 False

a = ' '

a.isspace() # True

b = ' abc'

b.isspace() # False

判斷是否為标題每個單詞的首字母大寫視為标題string.istitle() 如果 string 是标題化的(見 title())則返回 True,否則返回 False

a = 'Hello World'

a.istitle() # True

b = 'Hello world'

b.istitle() # False

将大寫字母變成小寫string.lower() 轉換 string 中所有大寫字符為小寫

a = 'ABCdef'

b = a.lower()print(b) # abcdef

将小寫字母變成大寫string.upper() 轉換 string 中的小寫字母為大寫

a = 'ABCdef'

b = a.upper()print(b) # ABCDEF

将小寫字母變成大寫同時将大寫字母變成小寫string.swapcase() 翻轉 string 中的大小寫

a = 'ABCdef'

b = a.swapcase()print(b) # abcDEF

把字符串左邊、右邊的空格或換行符去掉

a = ' haha xixi '

a.strip() # haha xixi

把字符串左邊的空格或換行符去掉

a = ' haha xixi '

a.lstrip() # 'haha xixi '

把字符串右邊的空格或換行符去掉

a = ' haha xixi '

a.rstrip() # ' haha xixi'

替換内容string.replace(str1, str2, num=string.count(str1)) 把 string 中的 str1 替換成 str2,如果 num 指定,則替換不超過 num 次

a = 'hello world world'

b = a.replace('l','p')print(b) # 'heppo worpd worpd'

c = a.replace('l','p',2) # 'heppo world world'

以指定字符作為分隔符将字符串中的元素分别取出來存入一個列表中string.split(str="", num=string.count(str)) 以 str 為分隔符切片 string,如果 num有指定值,則僅分隔 num 個子字符串

a = 'a:b:c:d:e'

b = a.split(':')print(b) # ['a', 'b', 'c', 'd', 'e']

c = a.split(':',2)print(c) # ['a', 'b', 'c:d:e']

以行為分隔符将字符串中的元素分别取出來存入一個列表中string.splitlines(num=string.count('\n')) 按照行分隔,返回一個包含各行作為元素的列表,如果 num 指定則僅切片 num 個行

a = 'hello world\nhello haha\nxixi\nhehe'

b = a.splitlines()print(b) # ['hello world', 'hello haha', 'xixi', 'hehe']

c = a.splitlines(2)print(c) # ['hello world\n', 'hello haha\n', 'xixi\n', 'hehe']

把字符串變成标題格式string.title() 返回"标題化"的 string,就是說所有單詞都是以大寫開始,其餘字母均為小寫

a = 'hello world'

b = a.title()print(b) # 'Hello World'

返回字符串 str 中最大的字母

a = 'abcGhijZ'

max(a) # j

返回字符串 str 中最小的字母

a = 'abcGhijZ'

min(a) # G

從指定位置将字符串分豁成三部分string.partition(str)有點像 find()和 split()的結合體從 str 出現的第一個位置起,把字符串string分成一個3元素的元組(string_pre_str,str,string_post_str)如果 string 中不包含str 則 string_pre_str == string

a = 'abcGhijZ'

b = a.partition('G')print(b) # ('abc', 'G', 'hijZ')

rpartitionstring.rpartition(str) 類似于 partition()函數,不過是從右邊開始查找

a = 'abcGhiGjZ'

b = a.rpartition('G')print(b) # ('abcGhi', 'G', 'jZ')

4 列表(list)

需求:把班上所有人的名字存起來

有同學說,不是學變量存儲了嗎,我就用變量存儲呗,呵呵,不嫌累嗎,同學,如果班裡有一百個人,你就得創建一百個變量啊,消耗大,效率低。

又有同學說,我用個大字符串不可以嗎,沒問題,你的确存起來了,但是,你對這個數據的操作(增删改查)将變得非常艱難,不是嗎,我想知道張三的位置,你怎麼辦?

在這種需求下,Python有了一個重要的數據類型----列表(list)

什麼是列表:列表(list)是Python以及其他語言中最常用到的數據結構之一。Python使用使用中括号 [ ] 來解析列表。列表是可變的(mutable)——可以改變列表的内容。

列表是一種容器類型:

  • 可以包含任意對象的有序集合,通過索引進行訪問其中的元素,是一種可變對象,其長度可變
  • 支持異構和任意嵌套
  • 支持在原處修改

對應操作:1.定義列表( [] )

names = ['tom','jerry','zhangshan','lisi']

2.查( [] )

names = ['tom','jerry','zhangshan','lisi']

# print(names[2])# print(names[0:3])# print(names[0:7])# print(names[-1])# print(names[2:3])# print(names[0:3:1])# print(names[3:0:-1])# print(names[:])

3.增(append,insert)insert 方法用于将對象插入到列表中,而append方法則用于在列表末尾追加新的對象

names.append('wangqing')

names.insert(2,'runtime')print(names)

4.改(重新賦值)

names=['zhangshan','lisi','tom','jerry']

names[3]='wangwu'

names[0:2]=['hehe','xixi']print(names)

5.删(remove,del,pop)

names.remove('xixi')del names[0]del names

names.pop() #注意,pop是有一個返回值的

6.其他操作6.1 countcount 方法統計某個元素在列表中出現的次數

In [1]: ['to', 'be', 'or', 'not', 'to', 'be'].count('to')

Out[1]: 2

In [2]: x = [[1,2], 1, 1, [2, 1, [1, 2]]]

In [3]: x.count(1)

Out[3]: 2

In [4]: x.count([1,2])

Out[4]: 1

6.2 extendextend 方法可以在列表的末尾一次性追加另一個序列中的多個值

In [5]: a = [1, 2, 3]

In [6]: b = [4, 5, 6]

In [7]: a.extend(b)

In [8]: a

Out[8]: [1, 2, 3, 4, 5, 6]

In [9]: b

Out[9]: [4, 5, 6]

extend 方法修改了被擴展的列表,而原始的連接操作( )則不然,它會返回一個全新的列表

In [10]: a = [1, 2, 3]

In [11]: b = [4, 5, 6]

In [12]: a b

Out[12]: [1, 2, 3, 4, 5, 6]

In [13]: a

Out[13]: [1, 2, 3]

In [14]: b

Out[14]: [4, 5, 6]

6.3 indexindex 方法用于從列表中找出某個值第一個匹配項的索引位置

names.index('xixi')

6.4 reversereverse 方法将列表中的元素反向存放

names.reverse()print(names_class2)

6.5 sortsort 方法用于在原位置對列表進行排序

x = [4, 6, 2, 1, 7, 9]

x.sort() #x.sort(reverse=True)

6.6 sortedsorted 方法會對對象進行排序并生成一個新的對象

In [1]: a = [1,3,5,2,10,8]In [2]: sorted(a)

Out[2]: [1, 2, 3, 5, 8, 10]In [3]: a

Out[3]: [1, 3, 5, 2, 10, 8]

6.7 深淺拷貝對于一個列表,我想複制一份怎麼辦呢?辦法一:重新賦值

a = [[1,2],3,4]b = [[1,2],3,4]

這是兩塊獨立的内存空間

這也沒問題,如果列表内容做夠大,你真的可以要每一個元素都重新寫一遍嗎?100個元素?1000個元素?辦法二:淺拷貝淺拷貝時,拷貝者與被拷貝者在内存中實際上是同一個對象引用

In [1]: a = [[1,2],3,4]

In [2]: b = a

In [3]: id(a)

Out[3]: 4485742792

In [4]: id(b)

Out[4]: 4485742792

In [5]: a[2] = 10

In [6]: a

Out[6]: [[1, 2], 3, 10]

In [7]: b

Out[7]: [[1, 2], 3, 10]

In [8]: a[0][0] = 3

In [9]: a

Out[9]: [[3, 2], 3, 10]

In [10]: b

Out[10]: [[3, 2], 3, 10]

辦法三:深拷貝深拷貝時,拷貝者與被拷貝者在内存中是兩個不同的對象引用通過分片賦值實現深拷貝

In [1]: a = [[1,2],3,4]

In [2]: b = a[:]

In [3]: id(a)

Out[3]: 4370272328

In [4]: id(b)

Out[4]: 4369162312

In [5]: a[1] = 10

In [6]: a

Out[6]: [[1, 2], 10, 4]

In [7]: b

Out[7]: [[1, 2], 3, 4]

In [8]: a[0][0] = 5

In [9]: a

Out[9]: [[5, 2], 10, 4]

In [10]: b

Out[10]: [[5, 2], 3, 4]

數據類型分幾種(數據類型)2

數據類型分幾種(數據類型)3

通過copy模塊的deepcopy方法來實現深複制

In [1]: import copy

In [2]: a = [[1,2],3,4]

In [3]: b = copy.deepcopy(a)

In [4]: id(a)

Out[4]: 4362280328

In [5]: id(b)

Out[5]: 4362553224

In [6]: a[1] = 100

In [7]: a

Out[7]: [[1, 2], 100, 4]

In [8]: b

Out[8]: [[1, 2], 3, 4]

In [9]: a[0][1] = 10

In [10]: a

Out[10]: [[1, 10], 100, 4]

In [11]: b

Out[11]: [[1, 2], 3, 4]

6.8 變量分解

In [1]: b,c = [1,2]

In [2]: b

Out[2]: 1

In [3]: c

Out[3]: 2

想一想:

  • 左邊變量比右邊多行嗎?
  • 右邊值比左邊多行嗎?
5 元組(tuple)

元組被稱為隻讀列表,即數據可以被查詢,但不能被修改,所以,列表的切片操作同樣适用于元組。

元組寫在小括号(())裡,元素之間用逗号隔開。

雖然tuple的元素不可改變,但它可以包含可變的對象,比如list列表。

構造包含 0 個或 1 個元素的元組比較特殊,所以有一些額外的語法規則:

t1 = () # 空元組

t2 = (10,) # 一個元素,需要在元素後添加逗号

作用:

  1. 對于一些數據我們不想被修改,可以使用元組;
  2. 元組可以在映射(和集合的成員)中當作鍵使用,而列表則不行
  3. 元組作為很多内建函數和方法的返回值存在

練習:購物車程序思路:

  1. 産品列表用什麼存
  2. 商品應該有編号,選擇編号就購買相應産品
  3. 用戶的銀行卡上錢應比商品價格高才能買
  4. 買完後應打印一個清單告知用戶購買了什麼,花了多少錢
6 字典(dict)

字典是Python中唯一的映射類型,采用鍵值對(key-value)的形式存儲數據。Python對key進行哈希函數運算,根據計算的結果決定value的存儲地址,所以字典是無序存儲的,且key必須是可哈希的。

可哈希表示key必須是不可變類型,如:數字、字符串、元組。

字典(dictionary)是除列表意外python之中最靈活的内置數據結構類型。列表是有序的對象結合,字典是無序的對象集合。兩者之間的區别在于:字典當中的元素是通過鍵來存取的,而不是通過偏移存取。

對應操作:1.創建字典{}

In [1]: dic1 = {'name':'wangqing','age':30,'sex':'male'}

In [2]: dic2 = dict((('name','wangqing'),))

In [3]: dic3 = {}.fromkeys(['name','age','salary'],'tom')

In [4]: dic1

Out[4]: {'name': 'wangqing', 'age': 30, 'sex': 'male'}

In [5]: dic2

Out[5]: {'name': 'wangqing'}

In [6]: dic3

Out[6]: {'name': 'tom', 'age': 'tom', 'salary': 'tom'}

2.增

In [1]: dic1 = {}

In [2]: dic1['name'] = 'tom'

In [3]: dic1['age'] = 20

In [4]: dic1

Out[4]: {'name': 'tom', 'age': 20}

In [5]: a = dic1.setdefault('name','wangqing')

In [6]: b = dic1.setdefault('ages',25)

In [7]: a

Out[7]: 'tom'

In [8]: b

Out[8]: 25

In [9]: dic1

Out[9]: {'name': 'tom', 'age': 20, 'ages': 25}

執行setdefault函數時當鍵已在字典中存在時用字典中原元素的值,當鍵在字典中不存在時,将新增該元素至字典中

3.查

dic1 = {'name': 'tom', 'age': 20}

# print(dic1['name'])

# print(dic1['names'])

#

# print(dic1.get('age',False))

# print(dic1.get('ages',False))

print(dic1.items())print(dic1.keys())print(dic1.values())

print('name' in dic3) # py2: dic3.has_key('name')print(list(dic3.values()))

4.改

dic1 = {'name': 'tom', 'age': 20}

dic1['name']='jerry'

dic2={'sex':'male','hobby':'book','age':23}

dic1.update(dic2)print(dic1)

5.删

dic1={'name': 'tom', 'age': 18,'class': 1}

# dic1.clear()# print(dic1)del dic1['name']

print(dic1)

a=dic1.popitem()

print(a,dic1)

# print(dic1.pop('age'))# print(dic1)

# del dic1# print(dic1)

6.字典方法6.1 dict.fromkeys

d1 = dict.fromkeys(['host1','host2','host3'],'Mac')print(d1)

d1['host1'] = 'xiaomi'print(d1)#######

d2 = dict.fromkeys(['host1','host2','host3'],['Mac','huawei'])print(d2)

d2['host1'][0] = 'xiaomi'print(d2)

6.2 dict.copy對字典進行淺複制,返回一個有相同鍵值的新字典

In [1]: a = {'name': 'tom','age': 23}

In [2]: d = a.copy()

In [3]: a

Out[3]: {'name': 'tom', 'age': 23}

In [4]: d

Out[4]: {'name': 'tom', 'age': 23}

In [5]: id(a)

Out[5]: 4378229208

In [6]: id(d)

Out[6]: 4382880464

6.3 字典的嵌套還用我們上面的例子,存取某班學生的信息,我們如果通過字典來完成,效果更佳

dic = {

'zhangshan': {

'age': 23,

'sex': 'male'

},

'lisi': {

'age': 20,

'sex': 'male'

},

'wangwu': {

'age': 27,

'sex': 'Female'

}

}

6.4 字典的排序sorted(dict)對字典進行排序,返回一個有序的包含字典所有key的列表

dic = {5:'555',2:'222',4:'444'}print(sorted(dic))

6.5 字典的遍曆

dic1={'name': 'tom', 'age': 20}

for i in dic1:

print(i,dic1[i])

for items in dic1.items():

print(items)

for keys,values in dic1.items():

print(keys,values)

7 集合(set)

集合是一個無序的,不重複的數據組合,它的主要作用如下:

  • 去重,把一個列表變成集合,就自動去重了
  • 關系測試,測試兩組數據之前的交集、差集、并集等關系

集合(set):把不同的元素組成一起形成集合,是Python基本的數據類型之一

集合元素(set elements):組成集合的成員(不可重複)

l1 = [1,2,'a','b']

s = set(l1)print(s) # {1, 2, 'a', 'b'}

l2=[1,2,1,'a','a']

s = set(l2)print(s) # {1, 2, 'a'}

集合對象是一組無序排列的可哈希的值:集合成員可以做字典的鍵

l1 = [[1,2],'a','b']

s = set(l1) # TypeError: unhashable type: 'list'print(s)

集合分類:可變集合、不可變集合

可變集合(set):可添加和删除元素,非可哈希的,不能用作字典的鍵,也不能做其他集合的元素

不可變集合(frozenset):與上面恰恰相反

l1 = [1,'a','b']

s = set(l1)

dic = {s: '123'} #TypeError: unhashable type: 'set'

集合的相關操作1.創建集合由于集合沒有自己的語法格式,隻能通過集合的工廠方法set()和frozenset()創建

s1 = set('wangqing')

s2= frozenset('tom')

print(s1,type(s1)) # {'a', 'g', 'q', 'i', 'n', 'w'} <class 'set'>print(s2,type(s2)) # frozenset({'m', 'o', 't'}) <class 'frozenset'> 'frozenset'>

2.訪問集合由于集合本身是無序的,所以不能為集合創建索引或切片操作,隻能循環遍曆或使用in、not in來訪問或判斷集合元素

s1 = set('wang')print('a' in s1) # Trueprint('b' in s1) # False# s1[1] # TypeError: 'set' object does not support indexing

for i in s1:

print(i)

3.集合添加元素

s1 = frozenset('wang')

s1.add(0) # AttributeError: 'frozenset' object has no attribute 'add' 'add'

s2 = set('wang')

s2.add('mm') # 添加的元素被當成一個整體添加print(s2) # {'a', 'mm', 'g', 'n', 'w'}

s2.update('HO') # 添加的元素被當成一個序列一個個添加進集合,\

# 當被添加的元素中有重複時隻會保留一個print(s2) # {'a', 'mm', 'g', 'H', 'O', 'n', 'w'}

4.集合删除4.1 删除集合元素

s1 = set('wangqing')

s1.remove('w') # 删除指定元素print(s1) # {'a', 'g', 'i', 'n', 'q'}

s1.pop() # 随機删除元素

s1.clear() # 清空元素

4.2 删除集合本身

s1 = set('wangqing')

del s1 # NameError: name 's1' is not defined

5.等價(==)與不等價(!=)

s1 = set('wangqing')

s2 = set('wangqi')

s1 == s2 # True

6.關系測試6.1 子集(<)s2是否完全被s1包含

s1 = set('wangqing')

s2 = set('wang')print('w' in s1) # Trueprint(s2 < s1) # True

print(s2.issubset(s1)) # True

6.2 超集(父集)(>)s1是否完全包含s2

s1 = set('wangqing')

s2 = set('wang')print(s1 > s2) # True

print(s1.issuperset(s2)) # True

6.3 交集(&)與集合and等價,交集符号的等價方法是intersection()取出的内容是兩組數據間都有的

s1 = set([1,2,3,4,5])

s2 = set([4,5,6,7,8])

s3 = s1 & s2print(s3) # {4, 5}

s1.intersection(s2) # {4, 5}

6.4 并集(|)聯合(union)操作與集合的or操作其實等價的,聯合符号有個等價的方法,union()把兩組數據中所有數據合并,重複的隻保留1個

s1 = set([1,2,3,4,5])

s2 = set([4,5,6,7,8])

s3 = s1 | s2print(s3) # {1, 2, 3, 4, 5, 6, 7, 8}

s1.union(s2) # {1, 2, 3, 4, 5, 6, 7, 8}

6.5 差集(-)等價方法是difference()s1中有而s2中沒有的元素

s1 = set([1,2,3,4,5])

s2 = set([4,5,6,7,8])

s3 = s1 - s2print(s3) # {1, 2, 3}

s1.difference(s2) # {1, 2, 3}

6.6 對稱差集(反向交集)(^)對稱差分是集合的(‘異或’),取得的元素屬于s1、s2但不同時屬于s1和s2.其等價方法symmetric_difference()取兩組數據中都有的元素之外的元素

s1 = set([1,2,3,4,5])

s2 = set([4,5,6,7,8])

s3 = s1 ^ s2print(s3) # {1, 2, 3, 6, 7, 8}

s1.symmetric_difference(s2) # {1, 2, 3, 6, 7, 8}

7.利用集合去重

l1 = [1,2,3,4,1,2,3,4]print(list(set(l1))) #[1, 2, 3, 4]

作業

寫一個三級菜單,要求如下:

  • 打印省、市、縣三級菜單
  • 可依次選擇進入各子菜單以及返回上一級
  • 可随時退出程序

所需知識點:

  • 列表
  • 字典
,
Comments
Welcome to tft每日頭條 comments! Please keep conversations courteous and on-topic. To fosterproductive and respectful conversations, you may see comments from our Community Managers.
Sign up to post
Sort by
Show More Comments
推荐阅读
單個5号電池充電器
單個5号電池充電器
手機的厚度與續航一直是一個不可調和的矛盾,雖然現在手機做的越來越薄,但是移動電源卻是越來越厚了。對于那些外出時手機沒電卻忘記帶移動電源的人來說,想要給手機充上電可不是一件簡單的事情。如果能用5号電池來充電,又怎麼樣呢?Nipper就是這樣的...
2024-05-03
陰極保護過程資料
陰極保護過程資料
陰極保護發明于1824年,一直到20世紀30年代才開始應用,而我國是從1958年開始研究應用陰極保護的。目前已經成功應用于海船、海港碼頭、埋地管道、地下電纜以及一些化工領域。采用陰極保護可以防止環境介質的電化學腐蝕,對點蝕、應力腐蝕、腐蝕疲...
2024-05-03
手機有什麼最好的修圖軟件
手機有什麼最好的修圖軟件
手機有什麼最好的修圖軟件?這個我最強烈推薦的一款移動端用的修圖軟件,Snapseed是谷歌旗下的産品這款軟件功能非常的強大,而且操作便捷,很容易上手,很喜歡這款軟件的局部調節功能和蒙闆功能,靠上下左右滑動來調節圖片的相關參數,調起色來特别有...
2024-05-03
小米手機有沒有錄屏功能
小米手機有沒有錄屏功能
小米手機有沒有錄屏功能?遊戲精彩瞬間沒人看到?抽到SSR卻隻能分享個截圖?教父母用手機,發微信解釋不清楚?本周MIUI開發版新增的屏幕錄制功能,可以一次性解決這些問題,我來為大家科普一下關于小米手機有沒有錄屏功能?下面希望有你要的答案,我們...
2024-05-03
這幾年,互聯網的發展趨勢越來越快,尤其是在人工智能的研究,阿裡,騰訊,百度在互聯網大會上更是講述了人工智能能的優勢,然而回過頭,我們看視頻網站這幾年的崛起的原因。你們現在手中最常用的視頻播放器是什麼?騰訊視頻,百度視頻,優酷視頻,還是愛奇藝...
2024-05-03
Copyright 2023-2024 - www.tftnews.com All Rights Reserved