Dictionary
Key-value format
The key defines the rule: 1, immutable types (numbers, strings, tuples). The only
Value definition rule: any type
Characteristics:
Disordered
Key must be unique
Define a dictionary
DIC = {' name ': ' Dong ', ' age ': 18}
Print (DIC)
# query
Print (dic[' name '])
Print (Dic.get ("Namea")) #有返回none
# add
dic[' gender ']= ' female ' #字典中的元素是无序的.
Print (DIC)
# Modify
dic[' name '] = ' Zhangsan '
Print (DIC)
#删除
Del dic[' name ']
Print (DIC)
Collection
Python's collection (set), like other languages, is an unordered set of distinct elements, with basic functionality including relationship testing and de-duplication elements. The collection object also supports mathematical operations such as Union (union), intersection (intersection), Difference (poor), and sysmmetric difference (symmetric difference sets). Because the collection is unordered, the sets does not support indexing, sharding, or other class sequence (sequence-like) operation.
Define a collection
List_1 = Set ([4,5,6])
List_2 = Set ([4,5,6,7,8,9])
Increase
List_1.add (11)
Print (list_1)
Delete
List_1.remove (10)
Print (list_1)
The length of the collection
Print (len (list_1))
Relationship Testing
Intersection (contains all elements that appear at the same time in two collections) symbol &
Print (List_1.intersection (list_2))
Ampersand (contains elements that appear in two collections) symbol |
Print (List_1.union (list_2))
Subtraction (contains all elements that appear in the collection list_1 but are not in the collection List_2) symbol-
Print (List_1.difference (list_2))
Subset
List_3 = set ([+])
Print (List_1.issubset (list_2))
Print (List_1.issubset (list_2))
Print (List_3.issubset (list_1))
Symmetric difference set (de-duplicated in two sets) ^
Print (List_1.symmetric_difference (list_2))
Working with files
#打开文件
Date = open ("Lyrice", encoding= "Utf-8"). Read ()
Print (date)
f = open ("Lyrice", encoding= "Utf-8")
#读取一行
Print (F.readline ())
Print (F.readline ())
#读取前五行.
For I in range (5):
Print (F.readline (). Strip ())
#写
A = open ("MyFile", "a")
A.write ("My name is zhangsan\n")
A.write ("Age is 18\n")
#关闭文件
A.close ()
The mode of opening the file is:
- R, read-only mode (default mode, file must exist, non-existent, throw exception)
- W, write-only mode (unreadable; not present, create; empty content if present)
- X, write-only mode (unreadable; not present, create, present error)
- A, append mode (readable; not present, create; append content only)
"+" means you can read and write a file at the same time
- r+, read/write (readable, writable)
- w+, write-read (readable, writable)
- x+, write-read (readable, writable)
- A +, read-write (readable, writable)
Python Learning Note 3