python基礎 dict和set

文章目錄

  • dict
  • set
      • 4.用集合為列表去重
      • 5.集合的增 add,update
      • 6.集合的刪 discard,remove,pop,clear
      • 7 集合運算
        • 7.1 子集(<或者issubset()方法)
        • 7.2并集(|或者union()方法)
        • 7.3 交集(&或者intersection())
        • 7.4 差集(-或者difference()方法)
        • 7.5 對稱集(^或者symmetric_difference())
      • 8.集合的copy(淺復制)

dict

Python內置了字典:dict的支持,dict全稱dictionary,在其他語言中也稱為map,使用鍵-值(key-value)存儲,具有極快的查找速度。

d = {‘Michael’: 95, ‘Bob’: 75, ‘Tracy’: 85}
下面使一些常用的方法:

def clear(self): # real signature unknown; restored from __doc__""" D.clear() -> None.  Remove all items from D. """passdef copy(self): # real signature unknown; restored from __doc__""" D.copy() -> a shallow copy of D """pass@staticmethod # known case
def fromkeys(*args, **kwargs): # real signature unknown""" Create a new dictionary with keys from iterable and values set to value. """passdef get(self, *args, **kwargs): # real signature unknown""" Return the value for key if key is in the dictionary, else default. """passdef items(self): # real signature unknown; restored from __doc__""" D.items() -> a set-like object providing a view on D's items """passdef keys(self): # real signature unknown; restored from __doc__""" D.keys() -> a set-like object providing a view on D's keys """passdef pop(self, k, d=None): # real signature unknown; restored from __doc__"""D.pop(k[,d]) -> v, remove specified key and return the corresponding value.If key is not found, d is returned if given, otherwise KeyError is raised"""passdef popitem(self, *args, **kwargs): # real signature unknown"""Remove and return a (key, value) pair as a 2-tuple.Pairs are returned in LIFO (last-in, first-out) order.Raises KeyError if the dict is empty."""passdef setdefault(self, *args, **kwargs): # real signature unknown"""Insert key with a value of default if key is not in the dictionary.Return the value for key if key is in the dictionary, else default."""passdef update(self, E=None, **F): # known special case of dict.update"""D.update([E, ]**F) -> None.  Update D from dict/iterable E and F.If E is present and has a .keys() method, then does:  for k in E: D[k] = E[k]If E is present and lacks a .keys() method, then does:  for k, v in E: D[k] = vIn either case, this is followed by: for k in F:  D[k] = F[k]"""passdef values(self): # real signature unknown; restored from __doc__""" D.values() -> an object providing a view on D's values """pass
  1. dict的key必須是不可變對象

    這是因為dict根據key來計算value的存儲位置,如果每次計算相同的key得出的結果不同,那dict內部就完全混亂了。這個通過key計算位置的算法稱為哈希算法(Hash)。

要保證hash的正確性,作為key的對象就不能變。在Python中,字符串、整數等都是不可變的,因此,可以放心地作為key。而list是可變的,就不能作為key。

set

set和dict類似,也是一組key的集合,但不存儲value。由于key不能重復,所以,在set中,沒有重復的key。

  1. 集合是一個無序可變不重復元素的序列(由于集合是無序的,所以不支持索引) , 集合的元素不能為可變類型(列表、字典、集合)
  2. 創建方式
    可以使用 { } 或 set( ) 創建集合,但是創建一個空集合時,只能使用set( )
  3. 集合的特點:
  • 無序性:集合中每個元素的地位是相同的,元素之間是無序的

  • 互異性:一個集合中,每個元素只能出現一次,任何元素之間都是不相同的

  • 確定性:給定一個集合,給定一個元素,該元素或屬于該集合,或不屬于該集合

4.用集合為列表去重

>>> list_1 = [1,4,6,8,1,4,6,8]
>>> list_1
[1, 4, 6, 8, 1, 4, 6, 8]
>>> set_1 = set(list_1)
>>> set_1
{8, 1, 4, 6}
>>> list_2=list(set_1)
>>> list_2
[8, 1, 4, 6]

5.集合的增 add,update

集合本省是可變的,所有可以增,刪
增的方法有:

  • add :增加單個元素
  • update:增加多個元素,還可以使用其他,列表,元組,字符串或者其他集合作為參數

例子:

>>> k = {'x','y'}
>>> k.add('r')
>>> k.add('v','f')
Traceback (most recent call last):File "<stdin>", line 1, in <module>
TypeError: add() takes exactly one argument (2 given)
>>> k.update('v','f')
>>> k
{'f', 'x', 'v', 'r', 'y'}

從最后輸出的值,我們發現,集合本身存儲是沒有順序的。

6.集合的刪 discard,remove,pop,clear

可以使用discard()和remove()方法刪除集合中特定的元素
兩者區別:如果集合中不存在指定元素,使用discard()保持不變,但是在這種情況下,remove()會引發KeyError.

>>> k
{'f', 'x', 'v', 'r', 'y'}
>>> k.discard('z')
>>> k.remove('z')
Traceback (most recent call last):File "<stdin>", line 1, in <module>
KeyError: 'z'
>>> k.remove('x')
>>> k
{'f', 'v', 'r', 'y'}
>>> k.discard('y')
>>> k
{'f', 'v', 'r'}

此外還可以使用pop()方法返回并刪除一個隨機元素

>>> k
{'f', 'v', 'r'}
>>> k.pop()
'f'
>>> k
{'v', 'r'}
>>> k.clear()
>>> k
set()
  • 由于集合和無序的,會隨機pop某個元素。

7 集合運算

運算符描述
s &= z把s更新為s和z的交集
s | =z把s更新為s和z的并集
s -= z把s更新為s和z的差集
s ^= z把s更新為s和z的對稱差集

7.1 子集(<或者issubset()方法)

>>> A = set('hello')
>>> B = set('world')
>>> A
{'l', 'h', 'o', 'e'}
>>> B
{'o', 'l', 'w', 'r', 'd'}
>>> c= set('he')
>>> c < A
True
>>> c <B
False
>>> c.issubset(A)
True

7.2并集(|或者union()方法)

>>> A= {'hello','world'}
>>> B= {'hello','beijing'}
>>> C= {'HELLO','Sh'}
>>> A|B
{'world', 'hello', 'beijing'}
>>> A.union(C)
{'world', 'hello', 'HELLO', 'Sh'}

7.3 交集(&或者intersection())

>>> A= {'hello','world'}
>>> B= {'hello','beijing'}
>>> C= {'HELLO','Sh'}
>>> A&B
{'hello'}
>>> A.intersection(B)
{'hello'}
>>> 

7.4 差集(-或者difference()方法)

A-B的差集是所有屬于A且 不屬于B的元素構成的集合

>>> A= {'hello','world'}
>>> B= {'hello','beijing'}
>>> C= {'HELLO','Sh'}
>>> A-B
{'world'}
>>> A.difference(B)
{'world'}
>>> A-C
{'world', 'hello'}

7.5 對稱集(^或者symmetric_difference())

兩個集合的對稱集是只屬于其中一個集合,而不屬于另外一個集合的元素組成的集合

>>> A= {'hello','world'}
>>> B= {'hello','beijing'}
>>> C= {'HELLO','Sh'}
>>> A ^B
{'beijing', 'world'}
>>> A.symmetric_difference(B)
{'beijing', 'world'}
>>> A.symmetric_difference(C)
{'world', 'hello', 'HELLO', 'Sh'}

可以理解為把兩個集合進行了去重,然后組合成一個新的集合。

8.集合的copy(淺復制)

s = {'hello','world','beijing',frozenset('kkf')}
print(s)
s2=s.copy()
print(s2)

結果如下:
在這里插入圖片描述

從運行結果來看,這里的copy是淺拷貝。

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/273828.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/273828.shtml
英文地址,請注明出處:http://en.pswp.cn/news/273828.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

python進階(第三章2)字典和集合

文章目錄3.8 集合論nee中的元素在haystack中出現的次數&#xff0c;可以在任何可迭代對象上3.8.1集合字面量3.8.2 集合推導3.8.3 集合操作3.9 dict和set的背后3.9.1 一個關于效率的實驗3.9.2 字典中的散列表1.散列值和相等性2.散列表算法獲取值&#xff1a;添加新的元素更新現有…

Android下實現GPS定位服務

1.申請Google API Key&#xff0c;參考前面文章 2.實現GPS的功能需要使用模擬器進行經緯度的模擬設置&#xff0c;請參考前一篇文章進行設置 3.創建一個Build Target為Google APIs的項目 4.修改Androidmanifest文件&#xff1a; view plain<uses-library android:name"…

python 鏈表 【測試題】

文章目錄注意&#xff1a;實例講解1 .鏈表基本功能2. 根據值刪除鏈表中的節點信息答案&#xff1a;3.反轉一個單鏈表信息答案4.合并兩個有序鏈表信息答案5.刪除排序鏈表中的重復元素信息答案6.移除鏈表元素信息7.環形鏈表信息進階思路答案注意&#xff1a; 這里的head是只存儲…

WebService應用一例,帶有安全驗證

1、創建WEB項目&#xff0c;添加WEB服務WebService1.asmx&#xff0c;代碼如下&#xff1a; 1 using System;2 using System.Collections.Generic;3 using System.Linq;4 using System.Web;5 using System.Web.Services;6 7 namespace WebService8 {9 /// <summary> …

linux集成開發環境

Linux操作系統的種種集成開發環境隨著Linux的逐漸興起&#xff0c;已經有為數眾多的程序在上面馳騁了&#xff0c;許多開發環境(Development Environment)也應運而生。好的開發環境一定是集成了編輯、編譯和調試等多項功能并且易于使用。本文介紹了一些在Linux上流行的開發環境…

mysql技術內幕《讀書筆記》

文章目錄1. mysql 體系結構和存儲引擎1.5 連接mysql1.5.11. mysql 體系結構和存儲引擎 1.5 連接mysql 連接mysql操作是一個連接進程和mysql數據庫實例進行通信。 本質是進程通信&#xff0c;常用的進程通信方式有管道&#xff0c;命名管道&#xff0c;命名字&#xff0c;TCP/…

DEDECMS全版本gotopage變量XSS ROOTKIT 0DAY

影響版本&#xff1a; DEDECMS全版本 漏洞描敘&#xff1a; DEDECMS后臺登陸模板中的gotopage變量未效驗傳入數據&#xff0c;導致XSS漏洞。 \dede\templets\login.htm 65行左右 <input type"hidden" name"gotopage" value"<?php if(!empty($g…

Android開源庫loopj的android-async-http的 JsonHttpResponseHandler 存在死循環GC_CONCURRENT

我現在用的是 AndroidAsyncHttp 1.4.4 版本&#xff0c;之前遇到一個很奇怪的問題&#xff0c; 當使用 JsonHttpResponseHandler 解析請求的頁面出現服務器錯誤或其他情況返回的內容不是 JSON 字符串時不會調用自己復寫實現的 onSuccess 或者 onFailure 方法&#xff0c;將會出…

python【進階】4.文本和字節序列

文章目錄1. 字符、碼位和字節表述4.1字符問題2. bytes、bytearray 和 memoryview 等二進制序列的獨特特性3. 全部 Unicode 和陳舊字符集的編解碼器4.避免和處理編碼錯誤5.處理文本文件的最佳實踐6.默認編碼的陷阱和標準 I/O 的問題7.規范化 Unicode 文本,進行安全的比較8.規范化…

C#序列化和反序列化

序列化和反序列化我們可能經常會聽到&#xff0c;其實通俗一點的解釋&#xff0c;序列化就是把一個對象保存到一個文件或數據庫字段中去&#xff0c;反序列化就是在適當的時候把這個文件再轉化成原來的對象使用。我想最主要的作用有&#xff1a; 1、在進程下次啟動時讀取上次保…

python【進階】5.一等函數(注銷)

在 Python 中,函數是一等對象。編程語言理論家把“一等對象”定義為滿足下述條件的程 序實體: 在運行時創建能賦值給變量或數據結構中的元素能作為參數傳給函數能作為函數的返回結果 在 Python 中,所有函數都是一等對象。 5.1 把函數視作對象 >>> def d(n): ... …

進程狀態轉換(了解)

進程三個基本狀態&#xff1a;就緒、阻塞、運行 這個比較簡單&#xff0c;進程創建后進入就緒狀態、然后若CPU空閑或能打斷CPU正在執行的進程&#xff08;優先級低的&#xff09;&#xff0c;那么就緒狀態轉換成運行態&#xff0c;運行時&#xff0c;進程需要用到其他資源&…

rebuild online意外終止導致ora-8104錯誤的實驗

rebuild online意外終止導致ora-8104錯誤的實驗 SQL> !oerr ora 810408104, 00000, "this index object %s is being online built or rebuilt"// *Cause: the index is being created or rebuild or waited for recovering // from the online (re)build // *Act…

關于range方法,如果你覺得python很簡單就錯了

前言&#xff1a;在系統學習迭代器之前&#xff0c;我一直以為 range() 方法也是用于生成迭代器的&#xff0c;現在卻突然發現&#xff0c;它生成的只是可迭代對象&#xff0c;而并不是迭代器&#xff01; 1、range() 是什么&#xff1f; 對于 range() 函數&#xff0c;有幾個注…

centos下crontab的使用

1.作用使用crontab命令可以修改crontab配置文件&#xff0c;然后該配置由cron公用程序在適當的時間執行&#xff0c;該命令使用權限是所有用戶。2.格式crontab [-u user] {-l | -r | -e}3.crontab命令選項: -u指定一個用戶, -l列出某個用戶的任務計劃, -r刪除某個用戶的任務, -…

關于python3中的包operator(支持函數式編程的包)

文章目錄1.functools2.operator.itemgetter3.operator.attrgetter雖然 Guido 明確表明,Python 的目標不是變成函數式編程語言,但是得益于 operator 和 functools 等包的支持,函數式編程風格也可以信手拈來。接下來的兩節分別介紹這兩 個包。 1.functools 示例1 使用 reduce 函…

collections 中的namedtuple

文章目錄namedtuple 基本用法namedtuple特性_make(iterable)_asdict()_replace(**kwargs)_fields_fields_defaults參考&#xff1a;namedtuple 基本用法 Tuple還有一個兄弟&#xff0c;叫namedtuple。雖然都是tuple&#xff0c;但是功能更為強大。對于namedtuple&#xff0c;你…

abap 中modify 的使用

1、modify table itab from wa Transporting f1 f2 ... 表示表itab中符合工作區wa 中關鍵字的一條數據的 f1 f2字段會被wa中對應的字段值更新。 modify用于更新和新增數據&#xff0c;當表中沒有數據時就新增&#xff0c;有就修改。 2、在使用binary search 時一定要先排序&am…

python[進階] 6.使用一等函數實現設計模式

文章目錄6.1.1 經典的“策略”模式6.1.2 使用函數實現“策略”模式6.1.3 選擇最佳策略&#xff1a;簡單的6.1.4 找出模塊中的全部6.2 “命令”模式6.1.1 經典的“策略”模式 為抽象基類&#xff08;Abstract Base Class&#xff0c;ABC&#xff09;&#xff0c;這么做是為了使…

2014阿里巴巴校園招聘筆試題 - 中南站

轉載于:https://www.cnblogs.com/gotodsp/articles/3530329.html