Import Math
Mlist = [' Tom ', ' Joy ', ' Mal ']
Mtuple = ("Tom")
mdict = {' Tom ': The ' Joy ': "The", ' Mal ': 77}
MSet = set ([+])
MSTR = ' ABCD '
Mgenerator = (x * x for x in range (1,10))
#切片
L = mlist
Print (L)
Print (L[0:3])
Print (L[0:2])
Print (L[-2:-1]) #支持最后一个节点为-1
Print (L[:1]) #默认为0时可以省略
#迭代
For x in Mlist:
Print (x)
For x in MSTR:
Print (x)
From collections Import iterable
Print (Isinstance (' abc ', iterable)) # whether STR can iterate
#同时引用了两个变量, it's very common in Python.
For x, y in [(1, 1), (2, 4), (3, 9)]:
Print (x, y)
#Python内置的enumerate函数可以把一个list变成索引-element pair so that the index and the element itself can be iterated at the same time in the For loop
For I,value in Enumerate (mlist):
Print (I,value)
#列表生产式
#列表生成式即List Comprehensions, is a very simple and powerful built-in Python build that can be used to create lists.
L = []
For x in range (1,10):
L.append (x)
Print (L)
#2
L = []
For x in range (1,10):
L.append (x*x)
Print (L)
#3
L = [x*x for x in range (1,10)]
Print (L)
#4 contains if judgment
L = [x*x for x in range (1,10) if x% 2 = = 0]
Print (L)
#5 Double Cycle
L=[m + N for m in ' abc ' for n in ' ABC ']
Print (L)
#6 Use list generation, you can write very concise code. For example, listing all file and directory names in the current directory, which can be implemented in a single line of code
Import OS #导入os模块
L = [d for D in Os.listdir ('. ')] # Os.listdir can list files and directories
#7for循环其实可以同时使用两个甚至多个变量, such as Dict's items (), can iterate both key and value at the same time:
For k,v in Mdict.items ():
Print (k, ' = ', V)
#生成器
#通过列表生成式, we can create a list directly. However, with memory limitations, the list capacity is certainly limited. Also, create a list with 1 million elements,
#不仅占用很大的存储空间, if we just need to access the first few elements, the space behind most of the elements is wasted.
#所以, if the list element can be calculated according to an algorithm, can we continue to calculate the subsequent elements in the process of the loop?
#这样就不必创建完整的list, thus saving a lot of space. In Python, this side loop computes the mechanism, called the generator: Generator.
#要创建一个generator, there are a number of ways. The first method is simple, as long as a list-generated [] is changed to (), a generator is created.
L = [x * x for x in range (1,10)] #list
g = (x * x for x in range (1,10)) #generator
#一个一个打印出来, you can get the next return value for generator with the next () function
Print (Next (mgenerator))
For x in Mgenerator:
Print (x)
#如果推算的算法比较复杂, you can also use a function to implement a For loop that has a similar list-generated type.
def fib (max):
N, a, b = 0, 0, 1
While N<max:
Print (b)
A, B = B, A + b
n = n + 1
Return ' Done '
#上面的函数和generator仅一步之遥. To turn the FIB function into a generator, you just need to change print (b) to yield B.
def fib (max):
N, a, b = 0, 0, 1
While N<max:
Yield b
A, B = B, A + b
n = n + 1
Return ' Done '
#这里, the most difficult thing to understand is that generator is not the same as the process of executing a function. The function is executed sequentially, the return statement is encountered, or the last line function statement is returned.
#而变成generator的函数, executes every time the next () is called, encounters a yield statement, returns, and resumes execution from the last yield statement returned.
Def odd ():
Print (' Step 1 ')
Yield 1
Print (' Step 2 ')
Yield (3)
Print (' Step 3 ')
Yield (3)
o = Odd ()
Print (Next (O), Next (O), Next (O))
#但是用for循环调用generator时, it is found that the return value of the return statement is not generator.
#如果想要拿到返回值, the stopiteration error must be captured, and the return value is contained in the value of stopiteration
g = fib (6)
While True:
Try
x = Next (g)
Print (' G: ', X)
Except Stopiteration as E:
Print (' Generator return value: ', E.value)
Break
Self-study Python notes