Data
The two main data structures in python are lists and dictionaries. Lists store data sequentially, and dictionaries are like small databases that use keys to efficiently store and retrieve data.
The type function can check the data type of a value or variable.
A sequence is a set of values that are arranged sequentially.pythonIn a3Types of built-in sequences: strings, tuples, and lists. The first positive index is0, pointing to the left. The first negative index is-1, pointing to the right side. You can also copy sub-sequences using slice notation, such asS[begin:end]From the indexbeginCopied toend-1The element. can be used+And*For stitching, the type of stitching sequence must be the same, and the tuple and list cannot be spliced. can be usedLenfunction to calculate the length. An expressionXin SCheck the sequencesWhether to include elementsx, if you include a returnTrueotherwise returnFalse。
Meta-group
Tuples are immutable sequences that contain 0 or more values. Tuples are enclosed in parentheses, where elements are separated by commas. If you want to modify a tuple, you must create a new tuple that reflects the change. Change the tuple to a list if you need to change it frequently. A single-element tuple must be followed by a comma-delimited list.
X in tup# if X is an element of Tup returns Truelen (Tup) #元组tup包含的元素数tup. Count (x) #元素x在元组tup中出现的次数tup. Index (x) #元组tup中第一个元素x的索引
List
Lists are mutable, and you can add, delete, or modify list elements without copying them. The list is enclosed in square brackets where the elements are separated by commas, the list can contain any type of value, and an empty list is represented by [] . When a program that processes a list looks for errors, it is often necessary to understand that the list elements point to their values, rather than include them. When there are elements in the list pointing to itself,Python is able to identify the derived references. The function reverse does not make a copy of the list, but instead deletes the elements of the list directly, so we say that the reversal is done in place.
S.append () #在列表s末尾添加元素xs. Count () #返回元素x在列表s中出现的次数s. Extend (LST) #将lst中所有元素都添加到s中s. Index (x) #返回第一次x的索引s. Insert (i,x) # Inserts an element x in front of the element specified by index I, with the result s[i]== Xs.pop (i) #删除并返回s中索引为i的元素s. Remove (x) #删除s中的第一个x元素s. Reverse () #反转s中元素的排列顺序s. Sort () # Sort elements in S in ascending order
List resolution , or filter by using list parsing
N*n for N in range (1,11) 2*n+7 for n in range (1,11) n**3 for n in range (1,11) n for n nums if n>0c for C in S if C.lowe R () C for C in S if C.lower () No in ' Aeiou '
Dictionary
ThePython dictionary is an extremely efficient data structure for storing key-value pairs. Dictionaries are also known as associative arrays and hash lists. The dictionary takes advantage of a clever programming trick - hashing. Essentially, each key value of a dictionary is converted to a numeric - hash value. When you access a value, convert the supplied key value to a hash value, and then jump to the corresponding position in the list.
The keys in the dictionary must be unique, and the keys are immutable. If you do not know beforehand whether a value is included in the dictionary, you can check it using keyin D . Returns Trueif key is contained in dictionary D .
D.items () #返回一个由字典d的键值对组成的视图d. Keys () #返回一个由字典d的键组成的视图d. VALUES () #返回一个由字典d的值组成的视图d. Get (Key) #返回与key相关联的值d. Pop (Key) # Delete key and return the value associated with it D.popitem () #返回字典d中的某个键值对d. Clear () #删除字典d的所有元素d. Copy () #复制字典dd. Fromkeys (s,t) #创建一个新字典, where the keys are from S, The value is from Td.setdefault (key,v) #如果key包含在字典d中则返回其值, otherwise returns V and adds (key,v) to dictionary D. D.update (e) #将e中的键值对添加到字典d中, E can be a dictionary, or a sequence of key-value pairs.
Collection
A collection is a series of non-repeating elements. A collection is similar to a dictionary, but contains only keys and no associated values. A collection is divided into two categories: mutable and immutable collections. The most common function of a collection is to delete duplicate elements in a sequence.
Input and output
python provides strong basic file I/O support.
Set the string format x= 1/81print (x) #0.0123456790123print (' value:%.2f '%x) #0.01print (' value:%.5f '%x) #0.01235
D integer o octal x lowercase hex x uppercase hex e lowercase scientific notation floating-point e capital scientific notation floating point F floating point s string percent character
You can also use the Format function to organize strings. ' My{0} has {1} '. Format (' dog ', ' fleas ') output: ' Mydog has fleas ' 1/81= {x} '. Format (x = 1/81) output: ' 1/81= 0.0123456790123 ' num= {x :. {d}f} '. Format (x = 1/81,d = 3) output: ' num= 0.012 ' num= {x:.{ D}F} '. Format (x = 1/81,d = 4) output: ' Num= 0.0123 '
Can be set by its precision, if this is not enough for you, then there is the last trick, module Ah, you can useCheetahModule orDjangoModule.
Read and write files
A file is a named collection of bits stored in a secondary storage device such as a hard disk,U -disk, memory bar, and so on. There are two types of files: text files and binaries. The former is essentially a string stored on disk, and the latter is a variety of other content.
OS.GETCWD () #返回当前工作目录的名称os. Listdir (P) #返回一个字符串列表, which contains all the file names in the folder specified by Path p Os.chdir (p) #将当前工作目录设置为路径pos. Path.isfile (P) # When the path p specifies the name of a file, returns Trueos.path.isdir (p) #当路径p指定的是一个文件夹的名称, returning Trueos.stat (fname) #返回有关fname的信息, such as size and last
If you just want to know the . py file under your current working directory, you can use the function below.
def list_py (path = None): if Path = = None:<pre name= "code" class= "HTML" > path= os.getcwd () <pre name= " Code "class=" HTML "> return[fname for fname in Os.listdir (path) if Os.path.isfile (fname) if Fname.endswith ('. Py ')]
Returns the sum of the sizes of all files in the current working directory.
def size_in_bytes (fname): return Os.stat (fname). St_sizedef cwd_size_in_bytes (): total= 0 for name in FILES_CWD (): total= Total + size_in_bytes (name) return
Working with text files
Read a text file line-wise
#r读取w写入a在文件末尾输入b二进制模式t文本模式 + Open File for read-write Def print_file1 (fname): f= Open (fname, ' R ') for line in F: print (line, End= ") F.close ()
F.read () #读取文件f. write (' helloworld! \ n ') #写入文件f. Seek (0) #让文件指针指向文件开头
Pickle
Pickle.dump Stores the data structure to disk, and then uses pickle.load to get the data structure from the disk.
Reading Web pages
Through the urllib module
Getting started with Python programming reading notes 2