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

多图旧版https://www.cnblogs.com/dunitian/p/9156097.html

在线预览http://github.lesschina.com/python/base/pop/3.list_tuple_dict_set.html

今天说说List、Tuple、Dict、Set。POP部分还有一些如Func、IO(也可以放OOP部分说)然后就说说面向对象吧。

先吐槽一下:Python面向对象真心需要规范,不然太容易走火入魔了 -_-!!! 汗,下次再说。。。

1.Python列表相关

1.1.列表定义、遍历

info_list=[] #空列表

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

遍历和之前一样,for 或者 while 都可以

for扩展:https://www.cnblogs.com/dunitian/p/9103673.html#forelse

In [1]:
  1. # 定义一个列表,列表虽然可以存不同类型,一般我们把相同类型的值存列表里面
  2. infos_list=["C#","JavaScript"]#定一个空列表 list=[]
In [2]:
  1. # for遍历
  2. for item in infos_list:
  3. print(item)
 
  1. C#
  2. JavaScript
In [3]:
  1. # while遍历
  2. i=0
  3. while i<len(infos_list):
  4. print(infos_list[i])
  5. i+=1
 
  1. C#
  2. JavaScript
 

1.2.列表添加

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

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

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

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

Python在指定位置插入列表是真的插入一个列表进去,C#是把里面的元素挨个插入进去

看后面的列表嵌套,是通过下标方式获取,eg: infos_list[0][1]

In [5]:
  1. # 添加~指定位置插入
  2. infos_list.insert(0,"Python")
  3. print(infos_list)
  4.  
  5. # 列表嵌套(后面会有扩展)
  6. temp_list=["test1","test2"]
  7. infos_list.insert(0,temp_list)
  8. print(infos_list)
 
  1. ['Python', 'C#', 'JavaScript', 'Java']
  2. [['test1', 'test2'], 'Python', 'C#', 'JavaScript', 'Java']
In [6]:
  1. infos_list #查看下现在列表是什么
Out[6]:
  1. [['test1', 'test2'], 'Python', 'C#', 'JavaScript', 'Java']
 

如果你想像C#那样把里面的元素挨个插入进去,可以用extend()

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

In [7]:
  1. # 添加一个列表
  2. infos_list2=["张三",21]#python里面的列表类似于List<object>
  3. infos_list.extend(infos_list2)
  4. print(infos_list)
 
  1. [['test1', 'test2'], 'Python', 'C#', 'JavaScript', 'Java', '张三', 21]
In [8]:
  1. #可以查看extend方法描述
  2. help(infos_list.extend)
 
  1. Help on built-in function extend:
  2.  
  3. extend(...) method of builtins.list instance
  4. L.extend(iterable) -> None -- extend list by appending elements from the iterable
 

1.3.列表删除

infos_list.pop() # 删除最后一个

infos_list.pop(0) # 删除指定索引,不存在就报错

In [9]:
  1. # 删除
  2. # pop()删除最后一个元素,返回删掉的元素
  3. infos_list.pop()
Out[9]:
  1. 21
In [10]:
  1. infos_list #查看一下列表
Out[10]:
  1. [['test1', 'test2'], 'Python', 'C#', 'JavaScript', 'Java', '张三']
In [11]:
  1. # 删除
  2. # pop(index) 删除指定下标元素,返回删掉的元素
  3. infos_list.pop(0)
Out[11]:
  1. ['test1', 'test2']
In [12]:
  1. infos_list #查看一下列表
Out[12]:
  1. ['Python', 'C#', 'JavaScript', 'Java', '张三']
In [13]:
  1. # 索引不存在就报错
  2. infos_list.pop(10)
 
  1. ---------------------------------------------------------------------------
  2. IndexError Traceback (most recent call last)
  3. <ipython-input-13-ad52d76f39b4> in <module>()
  4. 1 # 索引不存在就报错
  5. ----> 2infos_list.pop(10)
  6.  
  7. IndexError: pop index out of range
 

infos_list.remove("张三") # remove("")删除指定元素,不存在就报错

del infos_list[1] # 删除指定下标元素,不存在就报错

del infos_list # 删除集合(集合再访问就不存在了)不同于C#给集合赋null

关于del的删除后面还会说,这个和linux里面的ln引用删除类似

In [14]:
  1. # remove("")删除指定元素
  2. infos_list.remove("张三") #没有返回值
  3. print(infos_list)
 
  1. ['Python', 'C#', 'JavaScript', 'Java']
In [15]:
  1. infos_list.remove("dnt") # 不存在就报错
 
  1. ---------------------------------------------------------------------------
  2. ValueError Traceback (most recent call last)
  3. <ipython-input-15-9f9cdd692e63> in <module>()
  4. ----> 1infos_list.remove("dnt") # 不存在就报错
  5.  
  6. ValueError: list.remove(x): x not in list
In [16]:
  1. # del xxx[index] 删除指定下标元素
  2. del infos_list[1] #没有返回值
  3. print(infos_list)
 
  1. ['Python', 'JavaScript', 'Java']
In [17]:
  1. del infos_list[10] #不存在就报错
 
  1. ---------------------------------------------------------------------------
  2. IndexError Traceback (most recent call last)
  3. <ipython-input-17-b6366d96a6e9> in <module>()
  4. ----> 1del infos_list[10] #不存在就报错
  5.  
  6. IndexError: list assignment index out of range
In [18]:
  1. del infos_list # 删除集合(集合再访问就不存在了)
In [19]:
  1. infos_list # 集合再访问就不存在了
 
  1. ---------------------------------------------------------------------------
  2. NameError Traceback (most recent call last)
  3. <ipython-input-19-7de289d35755> in <module>()
  4. ----> 1infos_list # 集合再访问就不存在了
  5.  
  6. 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]:
  1. # 修改 xxx[index]=xx
  2. # 注意:一般不推荐在for循环里面修改
  3. infos_list2 #查看list2列表
Out[20]:
  1. ['张三', 21]
In [21]:
  1. infos_list2[1]="PHP" #只有下标修改一种方式
  2. print(infos_list2)
 
  1. ['张三', 'PHP']
In [22]:
  1. infos_list2[3]="GO" #不存在则异常
 
  1. ---------------------------------------------------------------------------
  2. IndexError Traceback (most recent call last)
  3. <ipython-input-22-ecf5fb72864d> in <module>()
  4. ----> 1infos_list2[3]="GO" #不存在则异常
  5.  
  6. IndexError: list assignment index out of range
In [23]:
  1. # 想按值修改需要先查下标再修改
  2. infos_list2.index("张三")
  3. infos_list2[0]="GO"
  4. print(infos_list2)
 
  1. ['GO', 'PHP']
In [24]:
  1. infos_list2.index("dnt")#不存在则异常
 
  1. ---------------------------------------------------------------------------
  2. ValueError Traceback (most recent call last)
  3. <ipython-input-24-6c57bb050f66> in <module>()
  4. ----> 1infos_list2.index("dnt")#不存在则异常
  5.  
  6. ValueError: 'dnt' is not in list
In [25]:
  1. # 知识面拓展: https://www.zhihu.com/question/49098374
  2. # 为什么python中不建议在for循环中修改列表?
  3. # 由于在遍历的过程中,删除了其中一个元素,导致后面的元素整体前移,导致有个元素成了漏网之鱼。
  4. # 同样的,在遍历过程中,使用插入操作,也会导致类似的错误。这也就是问题里说的无法“跟踪”元素。
  5. # 如果使用while,则可以在面对这样情况的时候灵活应对。
 

1.5.查询系列

in, not in, index, count

In [26]:
  1. # 查询 in, not in, index, count
  2. names_list=["张三","李四","王二麻子"]
In [27]:
  1. # 张三在列表中执行操作
  2. if "张三" in names_list:
  3. names_list.remove("张三")
  4. print(names_list)
 
  1. ['李四', '王二麻子']
In [28]:
  1. # 查看"大舅子"不在列表中执行操作
  2. if "大舅子" not in names_list:
  3. names_list.append("大舅子")
  4. print(names_list)
 
  1. ['李四', '王二麻子', '大舅子']
In [29]:
  1. # 查询王二麻子的索引
  2. print(names_list.index("王二麻子"))
 
  1. 1
In [30]:
  1. # 统计
  2. print(names_list.count("大舅子"))
  3. print(names_list.count("逆天"))
 
  1. 1
  2. 0
 

1.6.排序系列

num_list.reverse()# 倒序

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

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

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

1.7.列表切片

列表的切片操作很有用,主要跟数据相关,实际应用中和dict(后面会讲)联合使用

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

先说说 range

In [35]:
  1. # range扩展~创建一个整数列表
  2. # range(5)生成的序列是从0开始小于5的整数~[0,5)
  3. range_list=list(range(5))
  4. print(range_list)
 
  1. [0, 1, 2, 3, 4]
In [36]:
  1. # range(1,5)生成的序列是从1开始小于5的整数~[1,5)
  2. range_list=list(range(1,5))
  3. print(range_list)
 
  1. [1, 2, 3, 4]
In [37]:
  1. # 列表的切片操作很有用,主要跟数据相关,实际应用中和dict(后面会讲)联合使用
  2. # python切片语法:[start_index:end_index:step] (end_index取不到)
  3. top100=list(range(1,101)) #[1,101) => 1~100
  4. print(top100)
 
  1. [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]:
  1. # 取前10个元素
  2. top100[:10] #等价于:top100[0:10]
Out[38]:
  1. [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
In [39]:
  1. # 取最后10个元素
  2. top100[-10:]
Out[39]:
  1. [91, 92, 93, 94, 95, 96, 97, 98, 99, 100]
In [40]:
  1. # 前11~20(eg:第二页)
  2. top100[10:20]
Out[40]:
  1. [11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
In [41]:
  1. # 取80~90(eg:倒数第二页)
  2. top100[-20:-10]
Out[41]:
  1. [81, 82, 83, 84, 85, 86, 87, 88, 89, 90]
In [42]:
  1. # 前20个数,每两个取一个(eg:隔行换样式)
  2. top100[:20:2]
Out[42]:
  1. [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
In [43]:
  1. # 所有数每10个取一个(eg:test的时候十里挑一)
  2. top100[::10]
Out[43]:
  1. [1, 11, 21, 31, 41, 51, 61, 71, 81, 91]
 

1.8.Python列表相关的扩展

列表虽然可以存不同类型,一般我们把相同类型的值存列表里面,不同类型存字典里(key,value)

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

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

补充概念strtuple 也可以用切片操作哦~

str上次说了,这次说下Tuple(后面会继续说Tuple,先了解下吧)

In [47]:
  1. # 取前两个 返回元组
  2. (1,2,3,4,5)[:2]
Out[47]:
  1. (1, 2)
 

1.9.列表生成式

列表生成式是Python内置用来 创建list的生成式

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

传统方法是通过循环来实现,比如:

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

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

另一种写法:[x for x in range(1,11)] 来看看案例:

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

可能有人会问,第一种写法不是挺好的嘛,为什么要用第二种复杂写法?

看看下面案例你就知道它的强大了(能简写就简单)

现在有了range生成就更方便了,可如果我们需要 1~10的平方列表呢?`[1^2,2^2,....10^2]'

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

但是循环太繁琐,而列表生成式则可以用一行语句代替循环生成上面的list

[x * x for x in range(1, 11)] 你可以这样理解==>就是我们平时的for循环嘛,前面的参数是返回值罢了

In [53]:
  1. [x*x for x in range(1,11)]
Out[53]:
  1. [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
In [54]:
  1. # 把一个list中所有的字符串变成小写
  2. my_list = ['Hello', 'World', 'I', 'Love', 'You']
In [55]:
  1. [x.lower() for x in my_list]
Out[55]:
  1. ['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. # 1~10之间的偶数
  2. [x for x in range(1, 11) if x % 2 == 0]
Out[56]:
  1. [2, 4, 6, 8, 10]
In [57]:
  1. # 数学里面的全排列
  2. [x + y for x in 'ABC' for y in 'AB']
Out[57]:
  1. ['AA', 'AB', 'BA', 'BB', 'CA', 'CB']
 

其实你可以把他看成

  1. list1=[]
  2. for x in range(1,5):
  3. for y in range(1,4):
  4. list1.append((x,y))
In [58]:
  1. # 数学里面的坐标轴(元组马上就讲了,你可以看看)
  2. [(x,y) for x in range(1,5) for y in range(1,4)]
Out[58]:
  1. [(1, 1),
  2. (1, 2),
  3. (1, 3),
  4. (2, 1),
  5. (2, 2),
  6. (2, 3),
  7. (3, 1),
  8. (3, 2),
  9. (3, 3),
  10. (4, 1),
  11. (4, 2),
  12. (4, 3)]
In [59]:
  1. # (x,y,z)
  2. [(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),
  2. (1, 1, 2),
  3. (1, 2, 1),
  4. (1, 2, 2),
  5. (1, 3, 1),
  6. (1, 3, 2),
  7. (2, 1, 1),
  8. (2, 1, 2),
  9. (2, 2, 1),
  10. (2, 2, 2),
  11. (2, 3, 1),
  12. (2, 3, 2),
  13. (3, 1, 1),
  14. (3, 1, 2),
  15. (3, 2, 1),
  16. (3, 2, 2),
  17. (3, 3, 1),
  18. (3, 3, 2),
  19. (4, 1, 1),
  20. (4, 1, 2),
  21. (4, 2, 1),
  22. (4, 2, 2),
  23. (4, 3, 1),
  24. (4, 3, 2)]
 

2.CSharp列表相关

2.1.列表定义、遍历

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

遍历可以用foreach,for,while

In [60]:
  1. %%script csharp
  2. //# 定义一个列表
  3. // # infos_list=["C#","JavaScript"]#[]
  4. var infos_list = new List<object>() { "C#", "JavaScript" };
  5. // // # ###########################################################
  6. // // # # 遍历 for while
  7. // // # for item in infos_list:
  8. // // # print(item)
  9. foreach (var item in infos_list)
  10. {
  11. System.Console.WriteLine(item);
  12. }
  13. for (int i = 0; i < infos_list.Count; i++)
  14. {
  15. System.Console.WriteLine(infos_list[i]);
  16. }
  17. // # i=0
  18. // # while i<len(infos_list):
  19. // # print(infos_list[i])
  20. // # i+=1
  21. int j=0;
  22. while(j<infos_list.Count){
  23. Console.WriteLine(infos_list[j++]);
  24. }
 
  1. C#
  2. JavaScript
  3. C#
  4. JavaScript
  5. C#
  6. JavaScript
 

2.2.列表添加

Add,AddRange,Insert,InsertRange (和Python插入列表有些区别)

为了后面演示的方便,我这边定义一个自定义输出:

  1. private static void DivPrintList(List<object> list, string say = "")
  2. {
  3. Console.WriteLine($"\n{say}");
  4. foreach (var item in list)
  5. {
  6. System.Console.Write($"{item} ");
  7. }
  8. }

添加系列Code:

  1. var infos_list2 = new List<object>() { "张三", 21 };
  2.  
  3. // # # 增加
  4. // # # 末尾追加
  5. // # infos_list.append("Java")
  6. infos_list.Add("Java");
  7. DivPrintList(infos_list);
  8.  
  9. // # # 指定位置插入
  10. // # infos_list.insert(0,"Python")
  11. // # print(infos_list)
  12. infos_list.Insert(0,"Python");
  13. DivPrintList(infos_list);
  14.  
  15. // # # 添加一个列表
  16. // # infos_list2=["张三",21]#python里面的列表类似于List<object>
  17. // # infos_list.extend(infos_list2)
  18. // # print(infos_list)
  19. infos_list.AddRange(infos_list2);
  20. DivPrintList(infos_list);
  21.  
  22. /*C#有insertRange方法 */
  23. DivPrintList(infos_list2,"List2原来的列表:");
  24. infos_list2.InsertRange(0,infos_list);
  25. DivPrintList(infos_list2,"List2变化后列表:");

结果:

  1. # 末尾追加
  2. C# JavaScript Java
  3. # 指定位置插入
  4. Python C# JavaScript Java
  5. # 添加一个列表
  6. Python C# JavaScript Java 张三 21
  7. # insertRange方法
  8. List2原来的列表:
  9. 张三 21
  10. List2变化后列表:
  11. Python C# JavaScript Java 张三 21 张三 21
 

2.3.列表删除

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

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

清空列表infos_list.Clear();

  1. infos_list.RemoveAt(1);
  2. // infos_list.RemoveAt(10);//不存在则报错
  3. // infos_list.RemoveRange(0,1); //可以移除多个
  4. DivPrintList(infos_list);
  5. infos_list.Remove("我家在东北吗?"); //移除指定item,不存在不会报错
  6. DivPrintList(infos_list,"清空前:");
  7. infos_list.Clear();//清空列表
  8. DivPrintList(infos_list,"清空后:");

输出:

  1. Python JavaScript Java 张三 21
  2. 清空前:
  3. Python JavaScript Java 张三 21
  4. 清空后:
 

2.4.列表修改

基本上和Python一样

  1. DivPrintList(infos_list2);
  2. infos_list2[1] = "PHP";
  3. // infos_list2[3]="GO"; //不存在则异常
  4. DivPrintList(infos_list2);
  5. // # # 想按值修改需要先查下标再修改
  6. // # infos_list2.index("张三")
  7. // # infos_list2[0]="GO"
  8. // # print(infos_list2)
  9. // # # infos_list2.index("dnt")#不存在则异常
  10. int index = infos_list2.IndexOf("张三");
  11. infos_list2[index] = "GO";
  12. DivPrintList(infos_list2);
  13. infos_list2.IndexOf("dnt");//不存在返回-1

输出:

  1. Python C# JavaScript Java 张三 21 张三 21
  2. Python PHP JavaScript Java 张三 21 张三 21
  3. Python PHP JavaScript Java GO 21 张三 21

2.5.列表查询

IndexOfCount 这两个讲过了

查找用Contains,其他的用法你可以先看看

  1. // # 查询 in, not in, index, count
  2. // # names_list=["张三","李四","王二麻子"]
  3. var names_list=new List<string>(){"张三","李四","王二麻子"};
  4. // Console.WriteLine(names_list.Find(i=>i=="张三"));
  5. // Console.WriteLine(names_list.FirstOrDefault(i=>i=="张三"));
  6. Console.WriteLine(names_list.Exists(i=>i=="张三"));
  7. Console.WriteLine(names_list.Contains("张三"));

结果:

  1. True
  2. True
 

2.6.列表排序

  1. // # # 排序(sort, reverse 逆置)
  2. // # num_list=[1,3,5,88,7]
  3. var num_list = new List<object>() { 1, 3, 5, 88, 7 };
  4.  
  5. // # #倒序
  6. // # num_list.reverse()
  7. // # print(num_list)
  8. num_list.Reverse();
  9. DivPrintList(num_list);
  10. // # # 从小到大排序
  11. // # num_list.sort()
  12. // # print(num_list)
  13. num_list.Sort();
  14. DivPrintList(num_list);
  15.  
  16. // # # 从大到小
  17. // # num_list.sort(reverse=True)
  18. // # print(num_list)
  19. num_list.Sort();
  20. num_list.Reverse();
  21. DivPrintList(num_list);

输出:

  1. 7 88 5 3 1
  2. 1 3 5 7 88
  3. 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]:
  1. # 只能查询,其他操作和列表差不多(不可变)(最后面有可变扩展)
  2. test_tuple=("萌萌哒",1,3,5,"加息","加息")
In [62]:
  1. # 定义的扩展:
  2. test_tuple1=(1,) #(1)就不是元祖了
  3. test_tuple2=(2)
  4. print(type(test_tuple1))
  5. print(type(test_tuple2))
 
  1. <class 'tuple'>
  2. <class 'int'>
In [63]:
  1. # count index
  2. print(test_tuple.count("加息"))
  3. print(test_tuple.index("萌萌哒"))#没有find方法
 
  1. 2
  2. 0
In [64]:
  1. # 从特定位置查找,注意是左闭右开区间==>[1,4)
  2. print(test_tuple.index("加息", 1, 4))#查不到报错:ValueError: tuple.index(x): x not in tuple
 
  1. ---------------------------------------------------------------------------
  2. ValueError Traceback (most recent call last)
  3. <ipython-input-64-293cf803dc90> in <module>()
  4. 1 # 从特定位置查找,注意是左闭右开区间==>[1,4)
  5. ----> 2print(test_tuple.index("加息", 1, 4))#查不到报错:ValueError: tuple.index(x): x not in tuple
  6.  
  7. ValueError: tuple.index(x): x not in tuple
In [65]:
  1. #下标取
  2. print(test_tuple[0])
  3. print(test_tuple[-1])
 
  1. 萌萌哒
  2. 加息
In [66]:
  1. # 遍历方式1
  2. for item in test_tuple:
  3. print(item)
 
  1. 萌萌哒
  2. 1
  3. 3
  4. 5
  5. 加息
  6. 加息
In [67]:
  1. # 遍历方式2
  2. i=0
  3. while i<len(test_tuple):
  4. print(test_tuple[i])
  5. i+=1
 
  1. 萌萌哒
  2. 1
  3. 3
  4. 5
  5. 加息
  6. 加息
 

3.2.拆包、多维元组

先来说说 拆包相关的知识

a=(1,2)

b=a # 把a的引用给b

c,d=a # 不是把a分别赋值给c和d,等价于:c=a[0] d=a[1]

In [68]:
  1. # 后面讲字典遍历的时候会再提一下的
  2. a=(1,2)
  3. b=a#把a的引用给b
  4. #a里面两个值,直接给左边两个变量赋值了(有点像拆包了)
  5. c,d=a #不是把a分别赋值给c和d,等价于:c=a[0] d=a[1]
  6.  
  7. print(a)
  8. print(b)
  9. print(c)
  10. print(d)
 
  1. (1, 2)
  2. (1, 2)
  3. 1
  4. 2
In [69]:
  1. # 交换两数~元组的方式
  2. a=1
  3. b=2
  4. a,b=b,a # 写全:(a,b)=(b,a)
  5. print(a)
  6. print(b)
 
  1. 2
  2. 1
 

多维元组

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

some_tuples[0]

some_tuples[0][1]

In [70]:
  1. # 多维元组
  2. some_tuples=[(2,"萌萌哒"),(4,3)]
  3. some_tuples[0]
  4. some_tuples[0][1]
Out[70]:
  1. '萌萌哒'
 

3.3.可变元组

可变的元组(元组在定义的时候就不能变了,但是可以通过类似这种方式来改变)

案例里面用到了列表和字典(本章有讲解,这边你先看看)

参照C#的可变元组会更容易懂

In [71]:
  1. # 扩展:可变的元组(元组在定义的时候就不能变了,但是可以通过类似这种方式来改变)
  2. value_tuple = ("a", "1", ["mmd"],{"name":"dnt"})
In [72]:
  1. value_tuple
Out[72]:
  1. ('a', '1', ['mmd'], {'name': 'dnt'})
In [73]:
  1. value_tuple[2].append("test")
  2. print(value_tuple)
 
  1. ('a', '1', ['mmd', 'test'], {'name': 'dnt'})
In [74]:
  1. value_tuple[3]["wechat"]="dotnetcrazy"
  2. print(value_tuple)
 
  1. ('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监视信息)

  1. // 初始化
  2. var test_tuple = ("萌萌哒", 1, 3, 5, "加息", "加息"); //这种方式就是valueTuple了
  3. test_tuple.Item1 = "ddd";//可以修改值
  4. test_tuple.GetType();

需要说下的是,取值只能通过itemxxx来取了,然后就是valueTuple的值是可以修改的

下面直接进入应用场景:

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

贴一下方法:

  1. // public static (string city, string tel) GetCityAndTel()
  2. // {
  3. // return ("北京", "110");
  4. // }
  5. // 简化写法
  6. public static (string city, string tel) GetCityAndTel() => ("北京", "110");

再说一下,C#元组的方式交换两数:

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

PS:附上Python进行对比记忆:

  1. a=1
  2. b=2
  3. a,b=b,a # 写全:(a,b)=(b,a)

就说到这了,简单了解即可

 

5.Python字典系列

5.1.字典定义、遍历

主要解析一下这个:

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

每一次相当于取一个元组,那可以用之前讲的例子来简化了:c,d=a 等价于:c=a[0] d=a[1]

In [75]:
  1. infos_dict={"name":"dnt","web":"dkill.net"} #空字典定义 dict={}
In [76]:
  1. # 遍历keys
  2. for item in infos_dict.keys():
  3. print(item)
 
  1. name
  2. web
In [77]:
  1. #注意,如果你直接对infos遍历,其实只是遍历keys
  2. for item in infos_dict:
  3. print(item)
 
  1. name
  2. web
In [78]:
  1. # 遍历values
  2. for item in infos_dict.values():
  3. print(item)
 
  1. dnt
  2. dkill.net
In [79]:
  1. # 遍历键值对
  2. for item in infos_dict.items():
  3. print("Key:%s,Value:%s"%(item[0],item[1]))
 
  1. Key:name,Value:dnt
  2. Key:web,Value:dkill.net
In [80]:
  1. # 每一次相当于取一个元组,那可以用之前讲的例子来简化了:c,d=a #等价于:c=a[0] d=a[1]
  2. for k,v in infos_dict.items():
  3. print("Key:%s,Value:%s"%(k,v))
 
  1. Key:name,Value:dnt
  2. Key:web,Value:dkill.net
In [81]:
  1. # 活学活用,用列表生成式列表
  2. [k + ':' + v for k,v in infos_dict.items()]
Out[81]:
  1. ['name:dnt', 'web:dkill.net']
 

5.2.增加和修改

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

In [82]:
  1. # 增加 修改 (有就修改,没就添加)
  2. # 添加
  3. infos_dict["wechat"]="lll"
  4. print(infos_dict)
  5.  
  6. # 修改
  7. infos_dict["wechat"]="dotnetcrazy"
  8. print(infos_dict)
 
  1. {'name': 'dnt', 'web': 'dkill.net', 'wechat': 'lll'}
  2. {'name': 'dnt', 'web': 'dkill.net', 'wechat': 'dotnetcrazy'}
 

补充:dict内部存放的顺序和key放入的顺序是没有关系的

dict的key必须是 不可变对象,dict根据key进行hash算法,来计算value的存储位置

如果每次计算相同的key得出的结果不同,那dict内部就完全混乱了

测试结果:元组是可以作为Key的

In [83]:
  1. # dict的key必须是不可变对象的验证案例
  2. key1=(1,2,3)
  3. key2=[1,2,3]
  4. key3={"1":"2"}
In [84]:
  1. dic={}
In [85]:
  1. # 元组是不可变类型,可以当key
  2. dic[key1]="mmd"
In [86]:
  1. # dict根据key进行hash算法,来计算value的存储位置
  2. # 如果每次计算相同的key得出的结果不同,那dict内部就完全混乱了
  3. dic[key2]="dnt" # unhashable
 
  1. ---------------------------------------------------------------------------
  2. TypeError Traceback (most recent call last)
  3. <ipython-input-86-f185376d67c2> in <module>()
  4. 1 # dict根据key进行hash算法,来计算value的存储位置
  5. 2 # 如果每次计算相同的key得出的结果不同,那dict内部就完全混乱了
  6. ----> 3dic[key2]="dnt" # unhashable
  7.  
  8. TypeError: unhashable type: 'list'
In [87]:
  1. # 字典也不行
  2. dic[key3]="test"
 
  1. ---------------------------------------------------------------------------
  2. TypeError Traceback (most recent call last)
  3. <ipython-input-87-3f776e9bf984> in <module>()
  4. 1 # 字典也不行
  5. ----> 2dic[key3]="test"
  6.  
  7. TypeError: unhashable type: 'dict'
 

5.3.删除

删除系列

清空字典内容 infos_dict.clear()

删除指定内容 del infos_dict["name"]没有返回值) or pop(key)返回删除Key的值) 不存在都会报错

删除字典 del infos_dict

In [88]:
  1. infos_dict #查看列表
Out[88]:
  1. {'name': 'dnt', 'web': 'dkill.net', 'wechat': 'dotnetcrazy'}
In [89]:
  1. # 要删除一个key,用pop(key)方法,对应的value也会从dict中删除
  2. infos_dict.pop("wechat") #返回key对应的值
Out[89]:
  1. 'dotnetcrazy'
In [90]:
  1. infos_dict.pop("wechat") #key不存在,则报错
 
  1. ---------------------------------------------------------------------------
  2. KeyError Traceback (most recent call last)
  3. <ipython-input-90-dc5eeda55ffa> in <module>()
  4. ----> 1infos_dict.pop("wechat") #key不存在,则报错
  5.  
  6. KeyError: 'wechat'
In [91]:
  1. del infos_dict["name"] #没有返回值
  2. print(infos_dict)
 
  1. {'web': 'dkill.net'}
In [92]:
  1. del infos_dict["name"] #不存在就报错
 
  1. ---------------------------------------------------------------------------
  2. KeyError Traceback (most recent call last)
  3. <ipython-input-92-2a26e199752e> in <module>()
  4. ----> 1del infos_dict["name"] #不存在就报错
  5.  
  6. KeyError: 'name'
In [93]:
  1. #清空字典内容
  2. infos_dict.clear()
  3. print(infos_dict)
 
  1. {}
In [94]:
  1. # 删除字典
  2. del infos_dict
 

5.4.查询

查询系列:推荐:infos_dict.get("mmd") # 查不到不会异常

In [95]:
  1. infos_dict={"name":"dnt","web":"dkill.net"} #刚才被删掉了,我们重新定义一下
In [96]:
  1. infos_dict["name"]
Out[96]:
  1. 'dnt'
In [97]:
  1. infos_dict["mmd"] #查不到就异常
 
  1. ---------------------------------------------------------------------------
  2. KeyError Traceback (most recent call last)
  3. <ipython-input-97-bc0a122c60bb> in <module>()
  4. ----> 1infos_dict["mmd"] #查不到就异常
  5.  
  6. KeyError: 'mmd'
In [98]:
  1. # 要避免key不存在的错误,有两种办法
  2. # 一是通过in判断key是否存在:
  3. print("mmd" in infos_dict)
 
  1. False
In [99]:
  1. # 二是通过dict提供的get()方法
  2. infos_dict.get("name")
  3. print(infos_dict.get("mmd"))#如果key不存在,返回None
  4. print(infos_dict.get("mmd",-1))#也可以返回自己指定的value
 
  1. None
  2. -1
In [100]:
  1. # 查看帮助
  2. # help(infos_dict)
  3. len(infos_dict) #有几对key,value
  4. # infos_dict.has_key("name") #这个是python2里面的
Out[100]:
  1. 2
 

6.CSharp字典系列

6.1.定义、遍历

C#的字典操作大家比较熟悉了,而且挺简单的,就一笔带过了

  1. //定义
  2. var infos_dict = new Dictionary<string, object>{
  3. {"name","dnt"},
  4. {"web","dkill.net"}
  5. };
  6. //遍历
  7. foreach (KeyValuePair<string, object> kv in infos_dict)
  8. {
  9.   Console.WriteLine($"Key:{kv.Key},Value:{kv.Value}");
  10. }
 

6.2.增删改查

  1. //添加
  2. infos_dict.Add("wechat", "lll");
  3. infos_dict["wechat1"] = "lll";
  4.  
  5. //修改
  6. infos_dict["wechat"] = "dotnetcrazy";

删除系列:

  1. // 删除元素
  2. // # del infos_dict["name"]
  3. // # del infos_dict["dog"] #不存在就报错
  4. // # print(infos_dict)
  5. infos_dict.Remove("name");
  6. infos_dict.Remove("dog");//不存在不报错
  7. // 清空列表内容
  8. // # infos_dict.clear()
  9. // # print(infos_dict)
  10. infos_dict.Clear();

查询系列:

  1. // infos_dict["name"]
  2. // infos_dict["mmd"] #查不到就异常
  3. // infos_dict.get("name")
  4. // infos_dict.get("mmd")#查不到不会异常
  5. Console.WriteLine(infos_dict["name"]);
  6. // Console.WriteLine(infos_dict["mmd"]); //#查不到就异常
  7. // 先看看有没有 ContainsKey(key),看值就 ContainsValue(value)
  8. if (infos_dict.ContainsKey("mmd")) Console.WriteLine(infos_dict["mmd"]);
  9.  
  10. // len(infos_dict) #有几对key,value
  11. 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结合使用)

重复元素在自动被过滤(数学里面的集合也是没有重复元素的)

遍历:

  1. for item in my_set:
  2. print(item)
In [101]:
  1. # 先看个帮助文档
  2. help(set)
 
  1. Help on class set in module builtins:
  2.  
  3. class set(object)
  4. | set() -> new empty set object
  5. | set(iterable) -> new set object
  6. |
  7. | Build an unordered collection of unique elements.
  8. |
  9. | Methods defined here:
  10. |
  11. | __and__(self, value, /)
  12. | Return self&value.
  13. |
  14. | __contains__(...)
  15. | x.__contains__(y) <==> y in x.
  16. |
  17. | __eq__(self, value, /)
  18. | Return self==value.
  19. |
  20. | __ge__(self, value, /)
  21. | Return self>=value.
  22. |
  23. | __getattribute__(self, name, /)
  24. | Return getattr(self, name).
  25. |
  26. | __gt__(self, value, /)
  27. | Return self>value.
  28. |
  29. | __iand__(self, value, /)
  30. | Return self&=value.
  31. |
  32. | __init__(self, /, *args, **kwargs)
  33. | Initialize self. See help(type(self)) for accurate signature.
  34. |
  35. | __ior__(self, value, /)
  36. | Return self|=value.
  37. |
  38. | __isub__(self, value, /)
  39. | Return self-=value.
  40. |
  41. | __iter__(self, /)
  42. | Implement iter(self).
  43. |
  44. | __ixor__(self, value, /)
  45. | Return self^=value.
  46. |
  47. | __le__(self, value, /)
  48. | Return self<=value.
  49. |
  50. | __len__(self, /)
  51. | Return len(self).
  52. |
  53. | __lt__(self, value, /)
  54. | Return self<value.
  55. |
  56. | __ne__(self, value, /)
  57. | Return self!=value.
  58. |
  59. | __new__(*args, **kwargs) from builtins.type
  60. | Create and return a new object. See help(type) for accurate signature.
  61. |
  62. | __or__(self, value, /)
  63. | Return self|value.
  64. |
  65. | __rand__(self, value, /)
  66. | Return value&self.
  67. |
  68. | __reduce__(...)
  69. | Return state information for pickling.
  70. |
  71. | __repr__(self, /)
  72. | Return repr(self).
  73. |
  74. | __ror__(self, value, /)
  75. | Return value|self.
  76. |
  77. | __rsub__(self, value, /)
  78. | Return value-self.
  79. |
  80. | __rxor__(self, value, /)
  81. | Return value^self.
  82. |
  83. | __sizeof__(...)
  84. | S.__sizeof__() -> size of S in memory, in bytes
  85. |
  86. | __sub__(self, value, /)
  87. | Return self-value.
  88. |
  89. | __xor__(self, value, /)
  90. | Return self^value.
  91. |
  92. | add(...)
  93. | Add an element to a set.
  94. |
  95. | This has no effect if the element is already present.
  96. |
  97. | clear(...)
  98. | Remove all elements from this set.
  99. |
  100. | copy(...)
  101. | Return a shallow copy of a set.
  102. |
  103. | difference(...)
  104. | Return the difference of two or more sets as a new set.
  105. |
  106. | (i.e. all elements that are in this set but not the others.)
  107. |
  108. | difference_update(...)
  109. | Remove all elements of another set from this set.
  110. |
  111. | discard(...)
  112. | Remove an element from a set if it is a member.
  113. |
  114. | If the element is not a member, do nothing.
  115. |
  116. | intersection(...)
  117. | Return the intersection of two sets as a new set.
  118. |
  119. | (i.e. all elements that are in both sets.)
  120. |
  121. | intersection_update(...)
  122. | Update a set with the intersection of itself and another.
  123. |
  124. | isdisjoint(...)
  125. | Return True if two sets have a null intersection.
  126. |
  127. | issubset(...)
  128. | Report whether another set contains this set.
  129. |
  130. | issuperset(...)
  131. | Report whether this set contains another set.
  132. |
  133. | pop(...)
  134. | Remove and return an arbitrary set element.
  135. | Raises KeyError if the set is empty.
  136. |
  137. | remove(...)
  138. | Remove an element from a set; it must be a member.
  139. |
  140. | If the element is not a member, raise a KeyError.
  141. |
  142. | symmetric_difference(...)
  143. | Return the symmetric difference of two sets as a new set.
  144. |
  145. | (i.e. all elements that are in exactly one of the sets.)
  146. |
  147. | symmetric_difference_update(...)
  148. | Update a set with the symmetric difference of itself and another.
  149. |
  150. | union(...)
  151. | Return the union of sets as a new set.
  152. |
  153. | (i.e. all elements that are in either set.)
  154. |
  155. | update(...)
  156. | Update a set with the union of itself and others.
  157. |
  158. | ----------------------------------------------------------------------
  159. | Data and other attributes defined here:
  160. |
  161. | __hash__ = None
In [102]:
  1. # 定义一个set集合
  2. # set(iterable) -> new set object #列表就比较合适了
  3. my_set=set([1,2,1,"mmd"])
In [103]:
  1. # 数学里面也是用大括号表示的
  2. my_set # 重复元素在自动被过滤
Out[103]:
  1. {1, 2, 'mmd'}
In [104]:
  1. my_set=set((1,2,3,3,2))
In [105]:
  1. my_set
Out[105]:
  1. {1, 2, 3}
In [106]:
  1. # 只会存不重复的key值
  2. my_set=set({"name":"mmd","name":"ddd","age":22})
In [107]:
  1. my_set
Out[107]:
  1. {'age', 'name'}
In [108]:
  1. # 遍历 my_set
  2. for item in my_set:
  3. print(item)
 
  1. age
  2. name
In [109]:
  1. # list去重案例:
  2. my_list=[1,111,22,33,1,1,1]
  3. my_list=list(set(my_list))
  4. print(my_list)
 
  1. [1, 33, 22, 111]
 

7.2.增删改系列

添加元素:

add() 添加一个元素

update() 添加一些元素

删除系列:

discard() 有就删除,没有不会报错

In [110]:
  1. # 添加元素
  2. my_set.add("add") #没有返回值
  3. print(my_set)
 
  1. {'add', 'age', 'name'}
In [111]:
  1. # 添加一些元素
  2. my_set.update([1,4,3])
  3. print(my_set)
 
  1. {1, 3, 4, 'age', 'name', 'add'}
In [112]:
  1. my_set.update((6,7,9))
  2. print(my_set)
 
  1. {1, 3, 4, 6, 7, 9, 'age', 'name', 'add'}
In [113]:
  1. # 字符串被拆成字符存储
  2. my_set.update("Love")
  3. print(my_set)
 
  1. {1, 'o', 3, 4, 6, 7, 'L', 9, 'age', 'v', 'name', 'add', 'e'}
In [114]:
  1. ################### 删除系列 ###########################
In [115]:
  1. # 删除元素
  2. my_set.remove("mmd") # 不存在则报错
  3. print(my_set)
 
  1. ---------------------------------------------------------------------------
  2. KeyError Traceback (most recent call last)
  3. <ipython-input-115-1d51a9949e6e> in <module>()
  4. 1 # 删除元素
  5. ----> 2my_set.remove("mmd") # 不存在则报错
  6. 3 print(my_set)
  7.  
  8. KeyError: 'mmd'
In [116]:
  1. # 删除 name
  2. my_set.remove("name")
In [117]:
  1. my_set
Out[117]:
  1. {1, 3, 4, 6, 7, 9, 'L', 'add', 'age', 'e', 'o', 'v'}
In [118]:
  1. # pop删除
  2. # pop一般不用,说法不一,有些说删除第一个有些说随机
  3. # 了解就好了,不用管pop(全数字的时候,我测试的确删的是第一个)
  4. my_set.pop()
Out[118]:
  1. 1
In [119]:
  1. my_set
Out[119]:
  1. {3, 4, 6, 7, 9, 'L', 'add', 'age', 'e', 'o', 'v'}
In [120]:
  1. # 清空
  2. my_set.clear()
In [121]:
  1. my_set
Out[121]:
  1. set()
In [122]:
  1. # 有就删除,没有也不会报错
  2. my_set.discard("dnt") # 没有返回值
 

7.3.交、并、差、子集

In [123]:
  1. #利用运算符+set 实现数学方面的扩展
  2. set1=set([1,2,5])
  3. set2=set([2,4,6])
  4.  
  5. print(set1)
  6. print(set2)
 
  1. {1, 2, 5}
  2. {2, 4, 6}
In [124]:
  1. # 交集 A∩B={x|x∈A,且x∈B}
  2. set1 & set2
Out[124]:
  1. {2}
In [125]:
  1. # 并集 A∪B={x|x∈A,或x∈B}
  2. set1 | set2
Out[125]:
  1. {1, 2, 4, 5, 6}
In [126]:
  1. # 差集 A-B={x∣x∈A,且x∉B}
  2. set1 - set2
Out[126]:
  1. {1, 5}
In [127]:
  1. # 对称差集(互相没有的取出来)
  2. set1^set2
Out[127]:
  1. {1, 4, 5, 6}
In [128]:
  1. # Set方法实现交集
  2. set1.intersection(set2)
Out[128]:
  1. {2}
In [129]:
  1. # Set方法去重后的并集
  2. set1.union(set2)
Out[129]:
  1. {1, 2, 4, 5, 6}
In [130]:
  1. # 差集(把set1里面有的而set2里面没有的取出)
  2. set1.difference(set2)
Out[130]:
  1. {1, 5}
In [131]:
  1. # 对称差集(互相没有的取出来)
  2. set1.symmetric_difference(set2)
Out[131]:
  1. {1, 4, 5, 6}
In [132]:
  1. # 再定义两个Set用来进行下面调试
  2. set3=set([1,2])
  3. set4=set([7,8,9])
In [133]:
  1. # 子集(判断set3是否是set1的子集)
  2. set3.issubset(set1)
Out[133]:
  1. True
In [134]:
  1. # 父集(set1是否是set3的父集)
  2. set1.issuperset(set3)
Out[134]:
  1. True
In [135]:
  1. # 判断两个集合是否没有交集
  2. set1.isdisjoint(set4)
Out[135]:
  1. True
In [136]:
  1. # 反过来也一样
  2. set4.isdisjoint(set1)
Out[136]:
  1. True
In [137]:
  1. ################### 补集的扩展 ###########################
In [138]:
  1. # 补集
  2. set3=set(list(range(10)))
  3.  
  4. print(set3)
 
  1. {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
In [139]:
  1. # 【大前提】set2是set3的一个子集(set3包含于set2)
  2. set2.issubset(set3)
Out[139]:
  1. True
In [140]:
  1. # 这时候求差集,就等于求补集
  2. set3 - set2
Out[140]:
  1. {0, 1, 3, 5, 7, 8, 9}
In [141]:
  1. # 其他内容可以直接查看help
 

8.Python扩展

8.1.运算符扩展

+ 合并,* 复制,in 是否存在(字典是查key),not in 是否不存在(字典是查key

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

8.2.内置函数扩展

len,max,min,del

len(),这个就不说了,用的太多了

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

min(),这个和max一样用,最小值

In [147]:
  1. # len(item) 计算容器中元素个数
  2. print(len(test_str))
  3. print(len(test_list))
  4. print(len(test_dict))
 
  1. 13
  2. 3
  3. 2
In [148]:
  1. # max(item) 返回容器中元素最大值
  2. max(test_str)
Out[148]:
  1. 'w'
In [149]:
  1. # 这个注意一种情况(当然了,你按照之前说的规范,list里面放同一种类型就不会出错了)
  2. max(test_list) #TypeError: '>' not supported between instances of 'str' and 'int'
 
  1. ---------------------------------------------------------------------------
  2. TypeError Traceback (most recent call last)
  3. <ipython-input-149-7da4501a78c2> in <module>()
  4. 1 # 这个注意一种情况(当然了,你按照之前说的规范,list里面放同一种类型就不会出错了)
  5. ----> 2max(test_list) #TypeError: '>' not supported between instances of 'str' and 'int'
  6.  
  7. TypeError: '>' not supported between instances of 'str' and 'int'
In [150]:
  1. test_list=[1,3,5,7,9,2]
  2. print(max(test_list))
  3. print(max(test_dict)) #比较key
 
  1. 9
  2. wechat
In [151]:
  1. # min(item) 返回容器中元素最小值
  2. print(min(test_str))
  3. print(min(test_list))
  4. print(min(test_dict))
 
  1. .
  2. 1
  3. name
In [ ]:
  1. # del(item) 删除变量
  2. # del() or del xxx
In [ ]:
  1. # 可以忽略 cmp(item1, item2) 比较两个值
  2. # Python2里面有 cmp(1,2) ==> -1
  3. # cmp在比较字典数据时,先比较键,再比较值

Python3 与 C# 基础语法对比(List、Tuple、Dict、Set专栏)的更多相关文章

  1. Python3 与 C# 面向对象之~继承与多态 Python3 与 C# 面向对象之~封装 Python3 与 NetCore 基础语法对比(Function专栏) [C#]C#时间日期操作 [C#]C#中字符串的操作 [ASP.NET]NTKO插件使用常见问题 我对C#的认知。

    Python3 与 C# 面向对象之-继承与多态   文章汇总:https://www.cnblogs.com/dotnetcrazy/p/9160514.html 目录: 2.继承 ¶ 2.1.单继 ...

  2. Python3 与 C# 基础语法对比(Function专栏)

      Code:https://github.com/lotapp/BaseCode 多图旧版:https://www.cnblogs.com/dunitian/p/9186561.html 在线编程: ...

  3. Python3 与 C# 基础语法对比(就当Python和C#基础的普及吧)

      文章汇总:https://www.cnblogs.com/dotnetcrazy/p/9160514.html 多图旧排版:https://www.cnblogs.com/dunitian/p/9 ...

  4. Python3 与 NetCore 基础语法对比(Function专栏)

    Jupyter最新排版:https://www.cnblogs.com/dotnetcrazy/p/9175950.html 昨晚开始写大纲做demo,今天牺牲中午休息时间码文一篇,希望大家点点赞 O ...

  5. Python3 与 NetCore 基础语法对比(就当Python和C#基础的普及吧)

    Jupyter排版:https://www.cnblogs.com/dotnetcrazy/p/9102030.html 汇总系列:https://www.cnblogs.com/dunitian/p ...

  6. Python3 与 NetCore 基础语法对比(List、Tuple、Dict、Set专栏)

    Jupyter最新版:https://www.cnblogs.com/dotnetcrazy/p/9155310.html 在线演示:http://nbviewer.jupyter.org/githu ...

  7. Python3 与 NetCore 基础语法对比(String专栏)

    汇总系列:https://www.cnblogs.com/dunitian/p/4822808.html#ai Jupyter排版:https://www.cnblogs.com/dunitian/p ...

  8. Python3 与 C# 基础语法对比(String专栏)

      Code:https://github.com/lotapp/BaseCode 多图旧排版:https://www.cnblogs.com/dunitian/p/9119986.html 在线编程 ...

  9. python3笔记<一>基础语法

    随着AI人工智能的兴起,网络安全的普及,不论是网络安全工程师还是AI人工智能工程师,都选择了Python.(所以本菜也来开始上手Python) Python作为当下流行的脚本语言,其能力不言而喻,跨平 ...

随机推荐

  1. scoketio

    服务器代码let net = require('net'); // 创建服务器 let server = net.createServer(); // 定义一个数组 ,存放每一个连接服务器的客户端用户 ...

  2. java设计模式:面向对象设计的7个原则

    在软件开发中,为了提高软件系统的可维护性和可复用性,增加软件的可扩展性和灵活性,程序员要尽量根据7条原则来开发程序,从而提高软件开发效率,节约软件开发成本和维护成本. 这7条原则分别是:开闭原则.里氏 ...

  3. 为什么说Java中只有值传递(转载)

    出处:https://www.hollischuang.com/archives/2275 关于这个问题,在StackOverflow上也引发过广泛的讨论,看来很多程序员对于这个问题的理解都不尽相同, ...

  4. Eclipse在写java时的BUG

    要把这个关掉

  5. C# Note19: Windows安装包制作实践

    前言 最近在项目中需要不断更新新版本的software installer(软件安装包),于是便查阅资料,整理了下制作方法. NSIS安装包制作脚本 NSIS(Nullsoft Scriptable ...

  6. leetcode资料整理

    注:借鉴了 http://m.blog.csdn.net/blog/lsg32/18712353 在Github上提供leetcode有: 1.https://github.com/soulmachi ...

  7. java中去除字符串(String)中的换行字符(\r \n \t)

    例1: public class Test { public static void main(String[] args) { String s = "'sds gdasda" ...

  8. vue 中的slot属性(插槽)的使用

    总结如下: VUE中关于插槽的文档说明很短,语言又写的很凝练,再加上其和方法,数据,计算机等常用选项在使用频率,使用先后上的差别,这就有可能造成初次接触插槽的开发者容易产生“算了吧,回头再学,反正已经 ...

  9. 在python中定义二维数组

    发表于 http://liamchzh.0fees.net/?p=234&i=1 一次偶然的机会,发现python中list非常有意思. 先看一段代码 [py]array = [0, 0, 0 ...

  10. build/temp.linux-x86_64-2.7/_openssl.c:493:30: fatal error: openssl/opensslv.h: No such file or directory

    解决:apt-get install libssl-dev apt install python-dev(这个可能和那个错误关系不大)