Learning Python 10.11
142页开始
Dictionary:和list一样可以嵌套,但只能通过key访问。
1 Brasil = {"Ronaldo":9, "Rivaldo":10} 2 Brasil["Ronaldinho"]=11 3 print(Brasil) 4 #{'Rivaldo': 10, 'Ronaldo': 9, 'Ronaldinho': 11}
如何遍历Dictionaries:
1 for key in list(Brasil.keys()): 2 print(key, "=>", Brasil[key]) 3 #Rivaldo => 10 4 #Ronaldo => 9 5 #Ronaldinho => 11 6 for key in sorted(Brasil): #直接按key排序,不sorted则不排序 7 print(key, "=>", Brasil[key]) 8 #Rivaldo => 10 9 #Ronaldinho => 11 10 #Ronaldo => 9 11 numbers = list(Brasil.values()) 12 numbers.sort() 13 print(numbers) 14 #[9, 10, 11] 15 #本来想写一个反查的,找了一下还都是比较麻烦的,先这样吧
判断Dict是否存在某key除了try、in外还可以用get
1 print(Brasil.get("Carlos", 6)) 2 #6
Tuple:基本上类似List,但是不可变,因此仅包含String部分所列出的Immutable Sequence Type上的方法(而不含有类似List.append()类似的方法),同时单元素tuple一定要带有一个逗号
1 Nolan = ("Following", "Memento", "Prestige", "Batman", "Batman", "Inception", "Batman") 2 print(Nolan.count("Inception")) 3 #1 4 print(Nolan.index("Inception")) 5 #5
File(实为io.TextIOWrapper 继承自 io.IOBase):主要方法包括:
1 # -*- coding: utf-8 -*- 2 file = open("test.txt","r+") 3 print(file.read()) 4 #original contents in test.txt 5 file.write("hello") 6 print(file.readable()) 7 #True 8 file.close()
打开既读又写竟然不是w+而是r+,不甚理解。w+打开时read()出的内容是空白。
关于open中第二个参数的具体如下图:

其他Core Type:
Set:用set()或{'a', 'b', 'c'}声明。可以&,|,-
数字相关:decimal模块(import decimal)、fraction模块(from fraction import Fraction)(常用Number里已包括int、float、complex)
Boolean:True、False
None——type(None):NoneType
类型检查:可以用类似type(L)==list或isinstance(L, list)。但在python中这么做基本上都意味着破坏flexibility
自定义类:
自定义类
1 class Person: 2 def __init__(self, name, age): 3 self.name = name 4 self.age = age 5 def grow(self): 6 self.age += 1 #no a++ or ++a in python 7 def age_on_year(self, year): 8 self.age += year-2012 9 return self.age 10 11 Ronaldo = Person("Ronaldo", 2012-1976) 12 Messi = Person("Messi", 2012-1987) 13 Ronaldo.grow() 14 print(Ronaldo.age) 15 #37 16 print(Messi.age_on_year(2014)) 17 #27
才到157页,这还都是最基础的内容,这进度。只能用“驽马十驾,功在不舍。”安慰一下自己了。

浙公网安备 33010602011771号