Python3 與 C# 基礎語法對比(List、Tuple、Dict、Set專欄)

 

Code:https://github.com/lotapp/BaseCodehtml

多圖舊版http://www.javashuo.com/article/p-verefukg-g.htmlpython

在線預覽http://github.lesschina.com/python/base/pop/3.list_tuple_dict_set.htmllinux

今天說說List、Tuple、Dict、Set。POP部分還有一些如Func、IO(也能夠放OOP部分說)而後就說說面向對象吧。git

先吐槽一下:Python面向對象真心須要規範,否則太容易走火入魔了 -_-!!! 汗,下次再說。。。程序員

1.Python列表相關

1.1.列表定義、遍歷

info_list=[] #空列表github

infos_list=["C#","JavaScript"]web

遍歷和以前同樣,for 或者 while 均可以算法

for擴展:http://www.javashuo.com/article/p-bzacofvb-eb.html數組

In [1]:
# 定義一個列表,列表雖然能夠存不一樣類型,通常咱們把相同類型的值存列表裏面
infos_list=["C#","JavaScript"]#定一個空列表 list=[]
In [2]:
# for遍歷
for item in infos_list:
    print(item)
 
C#
JavaScript
In [3]:
# while遍歷
i=0
while i<len(infos_list):
    print(infos_list[i])
    i+=1
 
C#
JavaScript
 

1.2.列表添加

末尾追加 infos_list.append("Java")app

In [4]:
# 添加~末尾追加
infos_list.append("Java")
print(infos_list)
 
['C#', 'JavaScript', 'Java']
 

指定位置插入 infos_list.insert(0,"Python")

插入列表 infos_list.insert(0,temp_list)

Python在指定位置插入列表是真的插入一個列表進去,C#是把裏面的元素挨個插入進去

看後面的列表嵌套,是經過下標方式獲取,eg: infos_list[0][1]

In [5]:
# 添加~指定位置插入
infos_list.insert(0,"Python")
print(infos_list)

# 列表嵌套(後面會有擴展)
temp_list=["test1","test2"]
infos_list.insert(0,temp_list)
print(infos_list)
 
['Python', 'C#', 'JavaScript', 'Java']
[['test1', 'test2'], 'Python', 'C#', 'JavaScript', 'Java']
In [6]:
infos_list #查看下如今列表是什麼
Out[6]:
[['test1', 'test2'], 'Python', 'C#', 'JavaScript', 'Java']
 

若是你想像C#那樣把裏面的元素挨個插入進去,能夠用extend()

添加一個列表 infos_list.extend(infos_list2)

In [7]:
# 添加一個列表
infos_list2=["張三",21]#python裏面的列表相似於List<object>
infos_list.extend(infos_list2)
print(infos_list)
 
[['test1', 'test2'], 'Python', 'C#', 'JavaScript', 'Java', '張三', 21]
In [8]:
#能夠查看extend方法描述
help(infos_list.extend)
 
Help on built-in function extend:

extend(...) method of builtins.list instance
    L.extend(iterable) -> None -- extend list by appending elements from the iterable

 

1.3.列表刪除

infos_list.pop() # 刪除最後一個

infos_list.pop(0) # 刪除指定索引,不存在就報錯

In [9]:
# 刪除
# pop()刪除最後一個元素,返回刪掉的元素
infos_list.pop()
Out[9]:
21
In [10]:
infos_list #查看一下列表
Out[10]:
[['test1', 'test2'], 'Python', 'C#', 'JavaScript', 'Java', '張三']
In [11]:
# 刪除
# pop(index) 刪除指定下標元素,返回刪掉的元素
infos_list.pop(0)
Out[11]:
['test1', 'test2']
In [12]:
infos_list #查看一下列表
Out[12]:
['Python', 'C#', 'JavaScript', 'Java', '張三']
In [13]:
# 索引不存在就報錯
infos_list.pop(10)
 
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-13-ad52d76f39b4> in <module>()
      1 # 索引不存在就報錯
----> 2infos_list.pop(10)

IndexError: pop index out of range
 

infos_list.remove("張三") # remove("")刪除指定元素,不存在就報錯

del infos_list[1] # 刪除指定下標元素,不存在就報錯

del infos_list # 刪除集合(集合再訪問就不存在了)不一樣於C#給集合賦null

關於del的刪除後面還會說,這個和linux裏面的ln引用刪除相似

In [14]:
# remove("")刪除指定元素
infos_list.remove("張三") #沒有返回值
print(infos_list)
 
['Python', 'C#', 'JavaScript', 'Java']
In [15]:
infos_list.remove("dnt") # 不存在就報錯
 
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-15-9f9cdd692e63> in <module>()
----> 1infos_list.remove("dnt") # 不存在就報錯

ValueError: list.remove(x): x not in list
In [16]:
# del xxx[index] 刪除指定下標元素
del infos_list[1] #沒有返回值
print(infos_list)
 
['Python', 'JavaScript', 'Java']
In [17]:
del infos_list[10] #不存在就報錯
 
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-17-b6366d96a6e9> in <module>()
----> 1del infos_list[10] #不存在就報錯

IndexError: list assignment index out of range
In [18]:
del infos_list # 刪除集合(集合再訪問就不存在了)
In [19]:
infos_list # 集合再訪問就不存在了
 
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-19-7de289d35755> in <module>()
----> 1infos_list # 集合再訪問就不存在了

NameError: name 'infos_list' is not defined
 

1.4.列表修改

Python修改:(只能經過索引修改

infos_list2[1]="PHP" # 只有下標修改一種方式,不存在則異常

想按值修改須要先查下標再修改 eg:

infos_list2.index("張三")

infos_list2[0]="GO"

infos_list2.index("dnt") # 不存在則異常

In [20]:
# 修改 xxx[index]=xx
# 注意:通常不推薦在for循環裏面修改
infos_list2 #查看list2列表
Out[20]:
['張三', 21]
In [21]:
infos_list2[1]="PHP" #只有下標修改一種方式
print(infos_list2)
 
['張三', 'PHP']
In [22]:
infos_list2[3]="GO" #不存在則異常
 
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-22-ecf5fb72864d> in <module>()
----> 1infos_list2[3]="GO" #不存在則異常

IndexError: list assignment index out of range
In [23]:
# 想按值修改須要先查下標再修改
infos_list2.index("張三")
infos_list2[0]="GO"
print(infos_list2)
 
['GO', 'PHP']
In [24]:
infos_list2.index("dnt")#不存在則異常
 
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-24-6c57bb050f66> in <module>()
----> 1infos_list2.index("dnt")#不存在則異常

ValueError: 'dnt' is not in list
In [25]:
# 知識面拓展: https://www.zhihu.com/question/49098374
# 爲何python中不建議在for循環中修改列表?
# 因爲在遍歷的過程當中,刪除了其中一個元素,致使後面的元素總體前移,致使有個元素成了漏網之魚。
# 一樣的,在遍歷過程當中,使用插入操做,也會致使相似的錯誤。這也就是問題裏說的沒法「跟蹤」元素。
# 若是使用while,則能夠在面對這樣狀況的時候靈活應對。
 

1.5.查詢系列

in, not in, index, count

In [26]:
# 查詢 in, not in, index, count
names_list=["張三","李四","王二麻子"]
In [27]:
# 張三在列表中執行操做
if "張三" in names_list:
    names_list.remove("張三")
print(names_list)
 
['李四', '王二麻子']
In [28]:
# 查看"大舅子"不在列表中執行操做
if "大舅子" not in names_list:
    names_list.append("大舅子")
print(names_list)
 
['李四', '王二麻子', '大舅子']
In [29]:
# 查詢王二麻子的索引
print(names_list.index("王二麻子"))
 
1
In [30]:
# 統計
print(names_list.count("大舅子")) 
print(names_list.count("逆天")) 
 
1
0
 

1.6.排序系列

num_list.reverse()# 倒序

num_list.sort() # 從小到大排序

num_list.sort(reverse=True) # 從大到小

In [31]:
# 排序專用
num_list=[1,3,5,88,7]
In [32]:
# 倒序 reverse 逆置
num_list.reverse()
print(num_list)
 
[7, 88, 5, 3, 1]
In [33]:
# 從小到大排序
num_list.sort()
print(num_list)
 
[1, 3, 5, 7, 88]
In [34]:
# 從大到小
num_list.sort(reverse=True)
print(num_list)
 
[88, 7, 5, 3, 1]
 

1.7.列表切片

列表的切片操做頗有用,主要跟數據相關,實際應用中和dict(後面會講)聯合使用

python切片語法:[start_index:end_index:step]end_index取不到

先說說 range

In [35]:
# range擴展~建立一個整數列表
# range(5)生成的序列是從0開始小於5的整數~[0,5)
range_list=list(range(5))
print(range_list)
 
[0, 1, 2, 3, 4]
In [36]:
# range(1,5)生成的序列是從1開始小於5的整數~[1,5)
range_list=list(range(1,5))
print(range_list)
 
[1, 2, 3, 4]
In [37]:
# 列表的切片操做頗有用,主要跟數據相關,實際應用中和dict(後面會講)聯合使用
# python切片語法:[start_index:end_index:step] (end_index取不到)
top100=list(range(1,101)) #[1,101) => 1~100
print(top100)
 
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100]
In [38]:
# 取前10個元素
top100[:10] #等價於:top100[0:10]
Out[38]:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
In [39]:
# 取最後10個元素
top100[-10:]
Out[39]:
[91, 92, 93, 94, 95, 96, 97, 98, 99, 100]
In [40]:
# 前11~20(eg:第二頁)
top100[10:20]
Out[40]:
[11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
In [41]:
# 取80~90(eg:倒數第二頁)
top100[-20:-10]
Out[41]:
[81, 82, 83, 84, 85, 86, 87, 88, 89, 90]
In [42]:
# 前20個數,每兩個取一個(eg:隔行換樣式)
top100[:20:2]
Out[42]:
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
In [43]:
# 全部數每10個取一個(eg:test的時候十里挑一)
top100[::10]
Out[43]:
[1, 11, 21, 31, 41, 51, 61, 71, 81, 91]
 

1.8.Python列表相關的擴展

列表雖然能夠存不一樣類型,通常咱們把相同類型的值存列表裏面,不一樣類型存字典裏(key,value)

列表嵌套,獲取用下標的方式:num_list[5][1]

In [44]:
# #列表嵌套(列表也是能夠嵌套的)
num_list2=[33,44,22]
num_list.append(num_list2)
print(num_list)
 
[88, 7, 5, 3, 1, [33, 44, 22]]
In [45]:
# 輸出
print(num_list[5])
print(num_list[5][1]) #嵌套列表獲取值的方式
 
[33, 44, 22]
44
In [46]:
# 引入Null==>None
a=[1,2,3,4]
b=[5,6]
a=a.append(b)#a.append(b)沒有返回值
print(a)#None
 
None
 

補充概念strtuple 也能夠用切片操做哦~

str上次說了,此次說下Tuple(後面會繼續說Tuple,先了解下吧)

In [47]:
# 取前兩個 返回元組
(1,2,3,4,5)[:2]
Out[47]:
(1, 2)
 

1.9.列表生成式

列表生成式是Python內置用來 建立list的生成式

eg:要生成 list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

傳統方法是經過循環來實現,好比:

In [48]:
i=1
my_list=[]
while(i<11):
    my_list.append(i)
    i+=1
In [49]:
my_list
Out[49]:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
 

有了列表生成式就方便了 list(range(1, 11))(以前說列表切片的時候稍微引入了一下range)

另外一種寫法:[x for x in range(1,11)] 來看看案例:

In [50]:
list(range(1, 11))
Out[50]:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
In [51]:
[x for x in range(1,11)]
Out[51]:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
 

可能有人會問,第一種寫法不是挺好的嘛,爲何要用第二種複雜寫法?

看看下面案例你就知道它的強大了(能簡寫就簡單)

如今有了range生成就更方便了,可若是咱們須要 1~10的平方列表呢?`[1^2,2^2,....10^2]'

In [52]:
my_list=[]
for i in range(1,11):
    my_list.append(i*i)
    i+=1
print(my_list)
 
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
 

可是循環太繁瑣,而列表生成式則能夠用一行語句代替循環生成上面的list

[x * x for x in range(1, 11)] 你能夠這樣理解==>就是咱們平時的for循環嘛,前面的參數是返回值罷了

In [53]:
[x*x for x in range(1,11)]
Out[53]:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
In [54]:
# 把一個list中全部的字符串變成小寫
my_list = ['Hello', 'World', 'I', 'Love', 'You']
In [55]:
[x.lower() for x in my_list]
Out[55]:
['hello', 'world', 'i', 'love', 'you']
 

列表生成式的強大僅限於此嘛?No~

for循環後面還能夠加上if判斷 [x for x in range(1, 11) if x % 2 == 0]

多重for循環嵌套 [x + y for x in 'ABC' for y in 'AB']

In [56]:
# 1~10之間的偶數
[x for x in range(1, 11) if x % 2 == 0]
Out[56]:
[2, 4, 6, 8, 10]
In [57]:
# 數學裏面的全排列
[x + y for x in 'ABC' for y in 'AB']
Out[57]:
['AA', 'AB', 'BA', 'BB', 'CA', 'CB']
 

其實你能夠把他當作

list1=[]
for x in range(1,5):
    for y in range(1,4):
        list1.append((x,y))
In [58]:
# 數學裏面的座標軸(元組立刻就講了,你能夠看看)
[(x,y) for x in range(1,5) for y in range(1,4)]
Out[58]:
[(1, 1),
 (1, 2),
 (1, 3),
 (2, 1),
 (2, 2),
 (2, 3),
 (3, 1),
 (3, 2),
 (3, 3),
 (4, 1),
 (4, 2),
 (4, 3)]
In [59]:
# (x,y,z)
[(x,y,z) for x in range(1,5) for y in range(1,4) for z in range(1,3)]
Out[59]:
[(1, 1, 1),
 (1, 1, 2),
 (1, 2, 1),
 (1, 2, 2),
 (1, 3, 1),
 (1, 3, 2),
 (2, 1, 1),
 (2, 1, 2),
 (2, 2, 1),
 (2, 2, 2),
 (2, 3, 1),
 (2, 3, 2),
 (3, 1, 1),
 (3, 1, 2),
 (3, 2, 1),
 (3, 2, 2),
 (3, 3, 1),
 (3, 3, 2),
 (4, 1, 1),
 (4, 1, 2),
 (4, 2, 1),
 (4, 2, 2),
 (4, 3, 1),
 (4, 3, 2)]
 

2.CSharp列表相關

2.1.列表定義、遍歷

var infos_list = new List<object>() { "C#", "JavaScript" };

遍歷能夠用foreach,for,while

In [60]:
%%script csharp
//# 定義一個列表
// # infos_list=["C#","JavaScript"]#[]
var infos_list = new List<object>() { "C#", "JavaScript" };
// // # ###########################################################
// // # # 遍歷 for while
// // # for item in infos_list:
// // #     print(item)
foreach (var item in infos_list)
{
    System.Console.WriteLine(item);
}
for (int i = 0; i < infos_list.Count; i++)
{
    System.Console.WriteLine(infos_list[i]);
}
// # i=0
// # while i<len(infos_list):
// #     print(infos_list[i])
// #     i+=1
int j=0;
while(j<infos_list.Count){
   Console.WriteLine(infos_list[j++]);
}
 
C#
JavaScript
C#
JavaScript
C#
JavaScript
 

2.2.列表添加

Add,AddRange,Insert,InsertRange (和Python插入列表有些區別)

爲了後面演示的方便,我這邊定義一個自定義輸出:

private static void DivPrintList(List<object> list, string say = "")
{
    Console.WriteLine($"\n{say}");
    foreach (var item in list)
    {
        System.Console.Write($"{item} ");
    }
}

添加系列Code:

var infos_list2 = new List<object>() { "張三", 21 };

// # # 增長
// # # 末尾追加
// # infos_list.append("Java")
infos_list.Add("Java");
DivPrintList(infos_list);

// # # 指定位置插入
// # infos_list.insert(0,"Python")
// # print(infos_list)
infos_list.Insert(0,"Python");
DivPrintList(infos_list);

// # # 添加一個列表
// # infos_list2=["張三",21]#python裏面的列表相似於List<object>            
// # infos_list.extend(infos_list2)
// # print(infos_list)
infos_list.AddRange(infos_list2);
DivPrintList(infos_list);

/*C#有insertRange方法 */
DivPrintList(infos_list2,"List2原來的列表:");
infos_list2.InsertRange(0,infos_list);
DivPrintList(infos_list2,"List2變化後列表:");

結果:

# 末尾追加
C# JavaScript Java 

# 指定位置插入
Python C# JavaScript Java 

# 添加一個列表
Python C# JavaScript Java 張三 21 

# insertRange方法
List2原來的列表:
張三 21 
List2變化後列表:
Python C# JavaScript Java 張三 21 張三 21
 

2.3.列表刪除

移除指定索引infos_list.RemoveAt(1);

移除指定值infos_list.Remove(item);

清空列表infos_list.Clear();

infos_list.RemoveAt(1);
// infos_list.RemoveAt(10);//不存在則報錯
// infos_list.RemoveRange(0,1); //能夠移除多個
DivPrintList(infos_list);
infos_list.Remove("我家在東北嗎?"); //移除指定item,不存在不會報錯
DivPrintList(infos_list,"清空前:");
infos_list.Clear();//清空列表
DivPrintList(infos_list,"清空後:");

輸出:

Python JavaScript Java 張三 21 
清空前:
Python JavaScript Java 張三 21 
清空後:
 

2.4.列表修改

基本上和Python同樣

DivPrintList(infos_list2);
infos_list2[1] = "PHP";
// infos_list2[3]="GO"; //不存在則異常
DivPrintList(infos_list2);
// # # 想按值修改須要先查下標再修改
// # infos_list2.index("張三")
// # infos_list2[0]="GO"
// # print(infos_list2)
// # # infos_list2.index("dnt")#不存在則異常
int index = infos_list2.IndexOf("張三");
infos_list2[index] = "GO";
DivPrintList(infos_list2);
infos_list2.IndexOf("dnt");//不存在返回-1

輸出:

Python C# JavaScript Java 張三 21 張三 21 
Python PHP JavaScript Java 張三 21 張三 21 
Python PHP JavaScript Java GO 21 張三 21

2.5.列表查詢

IndexOfCount 這兩個講過了

查找用Contains,其餘的用法你能夠先看看

// # 查詢 in, not in, index, count
// # names_list=["張三","李四","王二麻子"]
var names_list=new List<string>(){"張三","李四","王二麻子"};
// Console.WriteLine(names_list.Find(i=>i=="張三"));
// Console.WriteLine(names_list.FirstOrDefault(i=>i=="張三"));
Console.WriteLine(names_list.Exists(i=>i=="張三"));
Console.WriteLine(names_list.Contains("張三"));

結果:

True
True
 

2.6.列表排序

// # # 排序(sort, reverse 逆置)
// # num_list=[1,3,5,88,7]
var num_list = new List<object>() { 1, 3, 5, 88, 7 };

// # #倒序
// # num_list.reverse()
// # print(num_list)
num_list.Reverse();
DivPrintList(num_list);
// # # 從小到大排序
// # num_list.sort()
// # print(num_list)
num_list.Sort();
DivPrintList(num_list);

// # # 從大到小
// # num_list.sort(reverse=True)
// # print(num_list)
num_list.Sort();
num_list.Reverse();
DivPrintList(num_list);

輸出:

7 88 5 3 1 
1 3 5 7 88 
88 7 5 3 1

2.7.列表嵌套和多維數組的擴展

列表嵌套不能像python那樣 下標操做,你能夠繼續循環遍歷,或者能夠定義多維數組來支持 num_list2[i][j]

定義:var num_list2 = new List<object>() { 33, 44, 22,new List<object>(){11,55,77} };

關於多維數組的案例能夠看我之前講解的Code:https://github.com/dunitian/LoTCodeBase/tree/master/NetCode/1.面向過程/02.數組系列

 

3.Python元組相關

3.1.元組定義、遍歷等

定義:xxx=(xxx,xxx,xxx)

定義一個元素的元組:xxx=(1,)

In [61]:
# 只能查詢,其餘操做和列表差很少(不可變)(最後面有可變擴展)
test_tuple=("萌萌噠",1,3,5,"加息","加息")
In [62]:
# 定義的擴展:
test_tuple1=(1,) #(1)就不是元祖了
test_tuple2=(2)
print(type(test_tuple1))
print(type(test_tuple2))
 
<class 'tuple'>
<class 'int'>
In [63]:
# count index
print(test_tuple.count("加息"))
print(test_tuple.index("萌萌噠"))#沒有find方法
 
2
0
In [64]:
# 從特定位置查找,注意是左閉右開區間==>[1,4)
print(test_tuple.index("加息", 1, 4))#查不到報錯:ValueError: tuple.index(x): x not in tuple
 
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-64-293cf803dc90> in <module>()
      1 # 從特定位置查找,注意是左閉右開區間==>[1,4)
----> 2print(test_tuple.index("加息", 1, 4))#查不到報錯:ValueError: tuple.index(x): x not in tuple

ValueError: tuple.index(x): x not in tuple
In [65]:
#下標取
print(test_tuple[0])
print(test_tuple[-1])
 
萌萌噠
加息
In [66]:
# 遍歷方式1
for item in test_tuple:
    print(item)
 
萌萌噠
1
3
5
加息
加息
In [67]:
# 遍歷方式2
i=0
while i<len(test_tuple):
    print(test_tuple[i])
    i+=1
 
萌萌噠
1
3
5
加息
加息
 

3.2.拆包、多維元組

先來講說 拆包相關的知識

a=(1,2)

b=a # 把a的引用給b

c,d=a # 不是把a分別賦值給c和d,等價於:c=a[0] d=a[1]

In [68]:
# 後面講字典遍歷的時候會再提一下的
a=(1,2)
b=a#把a的引用給b
#a裏面兩個值,直接給左邊兩個變量賦值了(有點像拆包了)
c,d=a #不是把a分別賦值給c和d,等價於:c=a[0] d=a[1]

print(a)
print(b)
print(c)
print(d)
 
(1, 2)
(1, 2)
1
2
In [69]:
# 交換兩數~元組的方式
a=1
b=2
a,b=b,a # 寫全:(a,b)=(b,a)
print(a)
print(b)
 
2
1
 

多維元組

some_tuples=[(2,"萌萌噠"),(4,3)]

some_tuples[0]

some_tuples[0][1]

In [70]:
# 多維元組
some_tuples=[(2,"萌萌噠"),(4,3)]
some_tuples[0]
some_tuples[0][1]
Out[70]:
'萌萌噠'
 

3.3.可變元組

可變的元組(元組在定義的時候就不能變了,可是能夠經過相似這種方式來改變)

案例裏面用到了列表和字典(本章有講解,這邊你先看看)

參照C#的可變元組會更容易懂

In [71]:
# 擴展:可變的元組(元組在定義的時候就不能變了,可是能夠經過相似這種方式來改變)
value_tuple = ("a", "1", ["mmd"],{"name":"dnt"})
In [72]:
value_tuple
Out[72]:
('a', '1', ['mmd'], {'name': 'dnt'})
In [73]:
value_tuple[2].append("test")
print(value_tuple)
 
('a', '1', ['mmd', 'test'], {'name': 'dnt'})
In [74]:
value_tuple[3]["wechat"]="dotnetcrazy"
print(value_tuple)
 
('a', '1', ['mmd', 'test'], {'name': 'dnt', 'wechat': 'dotnetcrazy'})
 

4.CSharp元組相關

逆天ValueTuple用的比較多,下面案例就是用的這個

元組系:https://msdn.microsoft.com/zh-cn/library/system.tuple.aspx

值元組:https://msdn.microsoft.com/zh-cn/library/system.valuetuple.aspx

C#中元組主要是方便程序員,不用天然能夠。好比:當你返回多個值是否還用ref out 或者返回一個list之類的?

這些都須要先定義,比較麻煩.元祖在這些場景用的比較多。

先說說基本使用:

初始化:var test_tuple = ("萌萌噠", 1, 3, 5, "加息", "加息");

這種方式就是valueTuple了(看vscode監視信息)

圖片

// 初始化
var test_tuple = ("萌萌噠", 1, 3, 5, "加息", "加息"); //這種方式就是valueTuple了
test_tuple.Item1 = "ddd";//能夠修改值
test_tuple.GetType();

須要說下的是,取值只能經過itemxxx來取了,而後就是valueTuple的值是能夠修改的

圖片

下面直接進入應用場景:

var result = GetCityAndTel();  //支持async/await模式
var city = result.city;
var tel = result.tel;
// 拆包方式:
var (city1, tel1) = GetCityAndTel();

貼一下方法:

// public static (string city, string tel) GetCityAndTel()
// {
//     return ("北京", "110");
// }
// 簡化寫法
public static (string city, string tel) GetCityAndTel() => ("北京", "110");

再說一下,C#元組的方式交換兩數:

int x = 1, y = 2;
(x, y) = (y, x);
Console.WriteLine("x: " + x + "  y: " + x);

PS:附上Python進行對比記憶:

a=1
b=2
a,b=b,a # 寫全:(a,b)=(b,a)

就說到這了,簡單瞭解便可

 

5.Python字典系列

5.1.字典定義、遍歷

主要解析一下這個:

for k,v in infos_dict.items():
  print("Key:%s,Value:%s"%(k,v))

每一次至關於取一個元組,那能夠用以前講的例子來簡化了:c,d=a 等價於:c=a[0] d=a[1]

In [75]:
infos_dict={"name":"dnt","web":"dkill.net"} #空字典定義 dict={}
In [76]:
# 遍歷keys
for item in infos_dict.keys():
    print(item)
 
name
web
In [77]:
#注意,若是你直接對infos遍歷,其實只是遍歷keys
for item in infos_dict:
    print(item)
 
name
web
In [78]:
# 遍歷values
for item in infos_dict.values():
    print(item)
 
dnt
dkill.net
In [79]:
# 遍歷鍵值對
for item in infos_dict.items():
    print("Key:%s,Value:%s"%(item[0],item[1]))
 
Key:name,Value:dnt
Key:web,Value:dkill.net
In [80]:
# 每一次至關於取一個元組,那能夠用以前講的例子來簡化了:c,d=a #等價於:c=a[0] d=a[1]
for k,v in infos_dict.items():
    print("Key:%s,Value:%s"%(k,v))
 
Key:name,Value:dnt
Key:web,Value:dkill.net
In [81]:
# 活學活用,用列表生成式列表
[k + ':' + v for k,v in infos_dict.items()]
Out[81]:
['name:dnt', 'web:dkill.net']
 

5.2.增長和修改

增長、修改infos_dict["wechat"]="dotnetcrazy" # 有就修改,沒就添加

In [82]:
# 增長 修改 (有就修改,沒就添加)
# 添加
infos_dict["wechat"]="lll"
print(infos_dict)

# 修改
infos_dict["wechat"]="dotnetcrazy"
print(infos_dict)
 
{'name': 'dnt', 'web': 'dkill.net', 'wechat': 'lll'}
{'name': 'dnt', 'web': 'dkill.net', 'wechat': 'dotnetcrazy'}
 

補充:dict內部存放的順序和key放入的順序是沒有關係的

dict的key必須是 不可變對象,dict根據key進行hash算法,來計算value的存儲位置

若是每次計算相同的key得出的結果不一樣,那dict內部就徹底混亂了

測試結果:元組是能夠做爲Key的

In [83]:
# dict的key必須是不可變對象的驗證案例
key1=(1,2,3)
key2=[1,2,3]
key3={"1":"2"}
In [84]:
dic={}
In [85]:
# 元組是不可變類型,能夠當key
dic[key1]="mmd"
In [86]:
# dict根據key進行hash算法,來計算value的存儲位置
# 若是每次計算相同的key得出的結果不一樣,那dict內部就徹底混亂了
dic[key2]="dnt" # unhashable
 
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-86-f185376d67c2> in <module>()
      1 # dict根據key進行hash算法,來計算value的存儲位置
      2 # 若是每次計算相同的key得出的結果不一樣,那dict內部就徹底混亂了
----> 3dic[key2]="dnt" # unhashable

TypeError: unhashable type: 'list'
In [87]:
# 字典也不行
dic[key3]="test"
 
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-87-3f776e9bf984> in <module>()
      1 # 字典也不行
----> 2dic[key3]="test"

TypeError: unhashable type: 'dict'
 

5.3.刪除

刪除系列

清空字典內容 infos_dict.clear()

刪除指定內容 del infos_dict["name"]沒有返回值) or pop(key)返回刪除Key的值) 不存在都會報錯

刪除字典 del infos_dict

In [88]:
infos_dict #查看列表
Out[88]:
{'name': 'dnt', 'web': 'dkill.net', 'wechat': 'dotnetcrazy'}
In [89]:
# 要刪除一個key,用pop(key)方法,對應的value也會從dict中刪除
infos_dict.pop("wechat") #返回key對應的值
Out[89]:
'dotnetcrazy'
In [90]:
infos_dict.pop("wechat") #key不存在,則報錯
 
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-90-dc5eeda55ffa> in <module>()
----> 1infos_dict.pop("wechat") #key不存在,則報錯

KeyError: 'wechat'
In [91]:
del infos_dict["name"] #沒有返回值
print(infos_dict)
 
{'web': 'dkill.net'}
In [92]:
del infos_dict["name"] #不存在就報錯
 
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-92-2a26e199752e> in <module>()
----> 1del infos_dict["name"] #不存在就報錯

KeyError: 'name'
In [93]:
#清空字典內容
infos_dict.clear()
print(infos_dict)
 
{}
In [94]:
# 刪除字典
del infos_dict
 

5.4.查詢

查詢系列:推薦:infos_dict.get("mmd") # 查不到不會異常

In [95]:
infos_dict={"name":"dnt","web":"dkill.net"} #剛纔被刪掉了,咱們從新定義一下
In [96]:
infos_dict["name"]
Out[96]:
'dnt'
In [97]:
infos_dict["mmd"] #查不到就異常
 
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-97-bc0a122c60bb> in <module>()
----> 1infos_dict["mmd"] #查不到就異常

KeyError: 'mmd'
In [98]:
# 要避免key不存在的錯誤,有兩種辦法
# 一是經過in判斷key是否存在:
print("mmd" in infos_dict)
 
False
In [99]:
# 二是經過dict提供的get()方法
infos_dict.get("name")
print(infos_dict.get("mmd"))#若是key不存在,返回None
print(infos_dict.get("mmd",-1))#也能夠返回本身指定的value
 
None
-1
In [100]:
# 查看幫助
# help(infos_dict)
len(infos_dict) #有幾對key,value 
# infos_dict.has_key("name") #這個是python2裏面的
Out[100]:
2
 

6.CSharp字典系列

6.1.定義、遍歷

C#的字典操做你們比較熟悉了,並且挺簡單的,就一筆帶過了

//定義
var infos_dict = new Dictionary<string, object>{
                {"name","dnt"},
                {"web","dkill.net"}
            };
//遍歷
foreach (KeyValuePair<string, object> kv in infos_dict)
{
  Console.WriteLine($"Key:{kv.Key},Value:{kv.Value}");
}
 

6.2.增刪改查

//添加
infos_dict.Add("wechat", "lll");
infos_dict["wechat1"] = "lll";

//修改
infos_dict["wechat"] = "dotnetcrazy";

刪除系列:

// 刪除元素
// # del infos_dict["name"]
// # del infos_dict["dog"] #不存在就報錯
// # print(infos_dict)
infos_dict.Remove("name");
infos_dict.Remove("dog");//不存在不報錯
// 清空列表內容
// # infos_dict.clear()
// # print(infos_dict)
infos_dict.Clear();

查詢系列:

// infos_dict["name"]
// infos_dict["mmd"] #查不到就異常            
// infos_dict.get("name")
// infos_dict.get("mmd")#查不到不會異常
Console.WriteLine(infos_dict["name"]);
// Console.WriteLine(infos_dict["mmd"]); //#查不到就異常
// 先看看有沒有 ContainsKey(key),看值就 ContainsValue(value)
if (infos_dict.ContainsKey("mmd")) Console.WriteLine(infos_dict["mmd"]);

// len(infos_dict) #有幾對key,value
Console.WriteLine(infos_dict.Count);
 

7.集合Set

7.1.定義、遍歷

定義:set(iterable)

eg:set([1,2,1,"mmd"]) 基本上能for循環的均可以(list,tuple,dict,str

若是是字符串,則拆分紅單個字符集合 set("abc")

集合Set注意個東西:(list去重通常就和set結合使用)

重複元素在自動被過濾(數學裏面的集合也是沒有重複元素的)

遍歷:

for item in my_set:
    print(item)
In [101]:
# 先看個幫助文檔
help(set)
 
Help on class set in module builtins:

class set(object)
 |  set() -> new empty set object
 |  set(iterable) -> new set object
 |  
 |  Build an unordered collection of unique elements.
 |  
 |  Methods defined here:
 |  
 |  __and__(self, value, /)
 |      Return self&value.
 |  
 |  __contains__(...)
 |      x.__contains__(y) <==> y in x.
 |  
 |  __eq__(self, value, /)
 |      Return self==value.
 |  
 |  __ge__(self, value, /)
 |      Return self>=value.
 |  
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |  
 |  __gt__(self, value, /)
 |      Return self>value.
 |  
 |  __iand__(self, value, /)
 |      Return self&=value.
 |  
 |  __init__(self, /, *args, **kwargs)
 |      Initialize self.  See help(type(self)) for accurate signature.
 |  
 |  __ior__(self, value, /)
 |      Return self|=value.
 |  
 |  __isub__(self, value, /)
 |      Return self-=value.
 |  
 |  __iter__(self, /)
 |      Implement iter(self).
 |  
 |  __ixor__(self, value, /)
 |      Return self^=value.
 |  
 |  __le__(self, value, /)
 |      Return self<=value.
 |  
 |  __len__(self, /)
 |      Return len(self).
 |  
 |  __lt__(self, value, /)
 |      Return self<value.
 |  
 |  __ne__(self, value, /)
 |      Return self!=value.
 |  
 |  __new__(*args, **kwargs) from builtins.type
 |      Create and return a new object.  See help(type) for accurate signature.
 |  
 |  __or__(self, value, /)
 |      Return self|value.
 |  
 |  __rand__(self, value, /)
 |      Return value&self.
 |  
 |  __reduce__(...)
 |      Return state information for pickling.
 |  
 |  __repr__(self, /)
 |      Return repr(self).
 |  
 |  __ror__(self, value, /)
 |      Return value|self.
 |  
 |  __rsub__(self, value, /)
 |      Return value-self.
 |  
 |  __rxor__(self, value, /)
 |      Return value^self.
 |  
 |  __sizeof__(...)
 |      S.__sizeof__() -> size of S in memory, in bytes
 |  
 |  __sub__(self, value, /)
 |      Return self-value.
 |  
 |  __xor__(self, value, /)
 |      Return self^value.
 |  
 |  add(...)
 |      Add an element to a set.
 |      
 |      This has no effect if the element is already present.
 |  
 |  clear(...)
 |      Remove all elements from this set.
 |  
 |  copy(...)
 |      Return a shallow copy of a set.
 |  
 |  difference(...)
 |      Return the difference of two or more sets as a new set.
 |      
 |      (i.e. all elements that are in this set but not the others.)
 |  
 |  difference_update(...)
 |      Remove all elements of another set from this set.
 |  
 |  discard(...)
 |      Remove an element from a set if it is a member.
 |      
 |      If the element is not a member, do nothing.
 |  
 |  intersection(...)
 |      Return the intersection of two sets as a new set.
 |      
 |      (i.e. all elements that are in both sets.)
 |  
 |  intersection_update(...)
 |      Update a set with the intersection of itself and another.
 |  
 |  isdisjoint(...)
 |      Return True if two sets have a null intersection.
 |  
 |  issubset(...)
 |      Report whether another set contains this set.
 |  
 |  issuperset(...)
 |      Report whether this set contains another set.
 |  
 |  pop(...)
 |      Remove and return an arbitrary set element.
 |      Raises KeyError if the set is empty.
 |  
 |  remove(...)
 |      Remove an element from a set; it must be a member.
 |      
 |      If the element is not a member, raise a KeyError.
 |  
 |  symmetric_difference(...)
 |      Return the symmetric difference of two sets as a new set.
 |      
 |      (i.e. all elements that are in exactly one of the sets.)
 |  
 |  symmetric_difference_update(...)
 |      Update a set with the symmetric difference of itself and another.
 |  
 |  union(...)
 |      Return the union of sets as a new set.
 |      
 |      (i.e. all elements that are in either set.)
 |  
 |  update(...)
 |      Update a set with the union of itself and others.
 |  
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |  
 |  __hash__ = None

In [102]:
# 定義一個set集合
# set(iterable) -> new set object #列表就比較合適了
my_set=set([1,2,1,"mmd"])
In [103]:
# 數學裏面也是用大括號表示的
my_set # 重複元素在自動被過濾
Out[103]:
{1, 2, 'mmd'}
In [104]:
my_set=set((1,2,3,3,2))
In [105]:
my_set
Out[105]:
{1, 2, 3}
In [106]:
# 只會存不重複的key值
my_set=set({"name":"mmd","name":"ddd","age":22})
In [107]:
my_set
Out[107]:
{'age', 'name'}
In [108]:
# 遍歷 my_set
for item in my_set:
    print(item)
 
age
name
In [109]:
# list去重案例:
my_list=[1,111,22,33,1,1,1]
my_list=list(set(my_list))
print(my_list)
 
[1, 33, 22, 111]
 

7.2.增刪改系列

添加元素:

add() 添加一個元素

update() 添加一些元素

刪除系列:

discard() 有就刪除,沒有不會報錯

In [110]:
# 添加元素
my_set.add("add") #沒有返回值
print(my_set)
 
{'add', 'age', 'name'}
In [111]:
# 添加一些元素
my_set.update([1,4,3])
print(my_set)
 
{1, 3, 4, 'age', 'name', 'add'}
In [112]:
my_set.update((6,7,9))
print(my_set)
 
{1, 3, 4, 6, 7, 9, 'age', 'name', 'add'}
In [113]:
# 字符串被拆成字符存儲
my_set.update("Love")
print(my_set)
 
{1, 'o', 3, 4, 6, 7, 'L', 9, 'age', 'v', 'name', 'add', 'e'}
In [114]:
################### 刪除系列 ###########################
In [115]:
# 刪除元素
my_set.remove("mmd") # 不存在則報錯
print(my_set)
 
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-115-1d51a9949e6e> in <module>()
      1 # 刪除元素
----> 2my_set.remove("mmd") # 不存在則報錯
      3 print(my_set)

KeyError: 'mmd'
In [116]:
# 刪除 name
my_set.remove("name")
In [117]:
my_set
Out[117]:
{1, 3, 4, 6, 7, 9, 'L', 'add', 'age', 'e', 'o', 'v'}
In [118]:
# pop刪除
# pop通常不用,說法不一,有些說刪除第一個有些說隨機
# 瞭解就行了,不用管pop(全數字的時候,我測試的確刪的是第一個)
my_set.pop()
Out[118]:
1
In [119]:
my_set
Out[119]:
{3, 4, 6, 7, 9, 'L', 'add', 'age', 'e', 'o', 'v'}
In [120]:
# 清空
my_set.clear()
In [121]:
my_set
Out[121]:
set()
In [122]:
# 有就刪除,沒有也不會報錯
my_set.discard("dnt") # 沒有返回值
 

7.3.交、並、差、子集

In [123]:
#利用運算符+set 實現數學方面的擴展
set1=set([1,2,5])
set2=set([2,4,6])

print(set1)
print(set2)
 
{1, 2, 5}
{2, 4, 6}
In [124]:
# 交集 A∩B={x|x∈A,且x∈B}
set1 & set2
Out[124]:
{2}
In [125]:
# 並集 A∪B={x|x∈A,或x∈B}
set1 | set2
Out[125]:
{1, 2, 4, 5, 6}
In [126]:
# 差集 A-B={x∣x∈A,且x∉B}
set1 - set2
Out[126]:
{1, 5}
In [127]:
# 對稱差集(互相沒有的取出來)
set1^set2
Out[127]:
{1, 4, 5, 6}
In [128]:
# Set方法實現交集
set1.intersection(set2)
Out[128]:
{2}
In [129]:
# Set方法去重後的並集
set1.union(set2)
Out[129]:
{1, 2, 4, 5, 6}
In [130]:
# 差集(把set1裏面有的而set2裏面沒有的取出)
set1.difference(set2)
Out[130]:
{1, 5}
In [131]:
# 對稱差集(互相沒有的取出來)
set1.symmetric_difference(set2)
Out[131]:
{1, 4, 5, 6}
In [132]:
# 再定義兩個Set用來進行下面調試
set3=set([1,2])
set4=set([7,8,9])
In [133]:
# 子集(判斷set3是不是set1的子集)
set3.issubset(set1)
Out[133]:
True
In [134]:
# 父集(set1是不是set3的父集)
set1.issuperset(set3)
Out[134]:
True
In [135]:
# 判斷兩個集合是否沒有交集
set1.isdisjoint(set4)
Out[135]:
True
In [136]:
# 反過來也同樣
set4.isdisjoint(set1)
Out[136]:
True
In [137]:
################### 補集的擴展 ###########################
In [138]:
# 補集
set3=set(list(range(10)))

print(set3)
 
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
In [139]:
# 【大前提】set2是set3的一個子集(set3包含於set2)
set2.issubset(set3)
Out[139]:
True
In [140]:
# 這時候求差集,就等於求補集
set3 - set2
Out[140]:
{0, 1, 3, 5, 7, 8, 9}
In [141]:
# 其餘內容能夠直接查看help
 

8.Python擴展

8.1.運算符擴展

+ 合併,* 複製,in 是否存在(字典是查key),not in 是否不存在(字典是查key

In [142]:
test_str="www.baidu.com"
test_list=[1,"d",5]
test_list1=[2,4,"n","t",3]
test_dict={"name":"dnt","wechat":"xxx"}
In [143]:
# + 合併 (不支持字典)
print(test_str+test_str)
print(test_list+test_list1)
 
www.baidu.comwww.baidu.com
[1, 'd', 5, 2, 4, 'n', 't', 3]
In [144]:
# * 複製 (不支持字典)
print(test_str*2)
print(test_list*2)
 
www.baidu.comwww.baidu.com
[1, 'd', 5, 1, 'd', 5]
In [145]:
# in 是否存在(字典是查key)
print("d" in test_str)          #True
print("d" in test_list)         #True
print("d" in test_dict)         #False
print("name" in test_dict)      #True
 
True
True
False
True
In [146]:
# not in 是否不存在(字典是查key)
print("z" not in test_str)      #True
print("z" not in test_list)     #True
print("z" not in test_dict)     #True
print("name" not in test_dict)  #False
 
True
True
True
False
 

8.2.內置函數擴展

len,max,min,del

len(),這個就不說了,用的太多了

max(),求最大值,dict的最大值是比較的key

min(),這個和max同樣用,最小值

In [147]:
# len(item) 計算容器中元素個數
print(len(test_str))
print(len(test_list))
print(len(test_dict))
 
13
3
2
In [148]:
# max(item) 返回容器中元素最大值
max(test_str)
Out[148]:
'w'
In [149]:
# 這個注意一種狀況(固然了,你按照以前說的規範,list裏面放同一種類型就不會出錯了)
max(test_list) #TypeError: '>' not supported between instances of 'str' and 'int'
 
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-149-7da4501a78c2> in <module>()
      1 # 這個注意一種狀況(固然了,你按照以前說的規範,list裏面放同一種類型就不會出錯了)
----> 2max(test_list) #TypeError: '>' not supported between instances of 'str' and 'int'

TypeError: '>' not supported between instances of 'str' and 'int'
In [150]:
test_list=[1,3,5,7,9,2]
print(max(test_list))
print(max(test_dict)) #比較key
 
9
wechat
In [151]:
# min(item) 返回容器中元素最小值
print(min(test_str))
print(min(test_list))
print(min(test_dict))
 
.
1
name
In [ ]:
# del(item)	        刪除變量
# del() or del xxx
In [ ]:
# 能夠忽略 cmp(item1, item2) 比較兩個值
# Python2裏面有 cmp(1,2) ==> -1 
# cmp在比較字典數據時,先比較鍵,再比較值
相關文章
相關標籤/搜索