Access to personal use only, please correct me if wrong also.
The reason is to use the advanced features of the code to simple . The fewer the code, the higher the development efficiency.
slice
Slicing identical lists and tuples. String is also similar.
For example in a list
L = ["Harden", "Durant", "Jordan", "Curry", "O'Neal"] print(L[0:3]) # 取前3个元素 # output:['Harden', 'Durant', 'Jordan'] print(L[:3]) # 第一个索引是0,还可以省略 # output:['Harden', 'Durant', 'Jordan'] print(L[1:3]) # 从索引1开始,取出2个元素出来 # output:['Durant', 'Jordan'] print(L[:]) # L[:]实际上是复制,这种复制是浅拷贝。 # output:['Harden', 'Durant', 'Jordan', 'Curry', "O'Neal"] print(L[::2]) # 第三个参数表示每N个取一个 # output:['Harden', 'Jordan', "O'Neal"] # 倒序切片:记住倒数第一个元素的索引是-1。倒序切片包含起始索引,不包含结束索引。 print(L[-2:]) # 取最后两个元素 # output:['Curry', "O'Neal"] print(L[:-2]) # 删去最后两个元素 # output:['Harden', 'Durant', 'Jordan'] print(L[-3:-1]) # 从索引-3开始,取出两个元素 # output:['Jordan', 'Curry'] print(L[-4:-1:2]) # 从索引-4开始,每两个取一个,到索引-1前结束 # output:['Durant', 'Curry']
Iteration
By for traversing strings, lists, tuples, dictionaries cycle. Traversing the equivalent of iterations .
If you learned C language or Java language all know, is done by iteration index. Look at the following code.
for (i=0; i<list.length; i++) { n = list[i]; }
The Python is through
for...in...
to complete. Look at the following code.for i in range(1, 100): if i % 7 == 0: print(i)
Obviously, Python iteration is removing the element itself, rather than the elements of the index.
If you want to get the index at the time of iterations, can
enumerate()
be obtained function.L = ["Harden", "Durant", "Jordan", "Curry", "O'Neal"] for index, name in enumerate(L): print(index, "--", name) # output: 0 -- Harden 1 -- Durant 2 -- Jordan 3 -- Curry 4 -- O'Neal
enumerate()
Function essentially put into a L[(0, "Harden"), (1, "Durant"), (2, "Jordan"), (3, "Curry"), (4, "O'Neal")]
Each element becomes the equivalent of a tuple. It can also be accessed through the index to go.
Note: This is only used to understand the concept of writing, the above method is recommended, because it's easy and simple.
for i in enumerate(L): index = i[0] name = i[1] print(index, "--", name)
Said earlier lists, tuples, now is that a rather special dictionary
Note: Before Python 3.6 version of the dictionary are unordered, this environment is Python 3.6.5 are ordered.
By default, the dictionary traversal content is key
d = {"PF":"Jordan", "SF":"Durant", "C":"O'Neal", "SG":"Harden", "PG":"Curry"} for key in d: print(key) # output: PF SF C SG PG
If you need to traverse value, use it
d.values()
.for value in d.values():
If the key, value needs to traverse, on the use of
d.items()
for k, v in d.items()
If it is determined an object is iterable it? Required by
collections
the moduleIterable
determines the type.Actually, I think there is no need, remember the common good. With so little to find out a way on the line.
from collections import Iterable print(isinstance("a", Iterable)) # 字符串是 print(isinstance([a, b, c], Iterable)) # 列表是 print(isinstance(123, Iterable)) # 整数不是
List of Formula
It is to achieve a single line of code list, and this list is flexible.
Generates a list
For example, before we want to generate a list of the most stupid way is to create one yourself.
Little bit better to use
list(range(1, 11))
, and then generates the 10 1 to 10 digits.Or slightly varied little
list(range(1, 10, 2))
, and then generate the odd-numbered 1-10.If you want to add some operations may be required for circulation to assist. But the cycle is too cumbersome.
Then we can use Python list of unique formula to solve this problem, but also a line of code.
For example, to generate [1 × 1,2 × 2, 3 × 3, ..., 10 × 10]
[x * x for x in range(1, 11)]
For example, to generate [1 × 2,3 × 4, 5 × 6, 7 × 8, ..., 99 × 100]
[x * (x + 1) for x in range(1, 100, 2)]
Conditions filter
As the name suggests it is that the formula can be added to the list inside
if
the statement.For example, a list of all strings in lowercase, non-string filter elements
L = [35, "Durant", "Jordan", "Curry", "O'Neal"] print([name.lower() for name in L if isinstance(name, str)])
Multilayer expression
A multilayer cycle, to find the three-digit symmetry, e.g., 101,121,232,222.
[x*100+y*10+z for x in range(1,10) for y in range(10) for z in range(10) if x == z]
Builder
Mentioned formula list, the list also understand that the capacity will be limited. Taking up too much storage space.
If the elements of a list can be calculated by an algorithm out, you can save a lot of space, and this mechanism is the generator.
Create a generator, the easiest way is to use
()
to represent. E.gg = (x * x for x in range(10)) print(g) # output:<generator object <genexpr> at 0x00000239CCD59C50> # 可以看到这是一个生成器,怎么去获取呢?使用next()函数,一个一个打印出来。 print(next(g)) # output:0 print(next(g)) # output:1 # 需要注意的是:生成器保存的是算法。 # 上面的next()方法是有点傻的,如果没有元素了,还会调用异常。所以一般都是用for循环去遍历的。 for n in g: print(n, end=",") # output:0,1,4,9,16,25,36,49,64,81,
Said earlier, the generator is stored algorithm , if the algorithm complexity, list generation type of
for
cycle can not be achieved, you can use the function to achieve .In Fibonacci number, it is the rule in addition to the first and second number, by any of a number obtained by adding the first two numbers.
1,1,2,3,5,8,13,21,34,55,...
Clearly, write to the list with the formula, however, a function can be easily achieved.
def fib(max): n, a, b = 0, 0, 1 while n < max: print(b) a, b = b, a + b n = n + 1 return 'over' print(fib(6)) # output: 1 1 2 3 5 8 over
As described above, this
fib
function implements the rules of the algorithm, in line with the overall logic generator. But he has always been a function.We need a keyword the yield , into the function generator. This is another way to create a generator.
The implementation process: first iteration, will perform to
yield b
, and then returns the value of b, return value as the first iteration, the second iteration, will not go to perform a function, but fromyield b
the next statement continues, until it encounters againyield
. So on and so forth.def fib(max): n, a, b = 0, 0, 1 while n < max: yield b a, b = b, a + b n = n + 1 return 'over' print(fib(6)) # <generator object fib at 0x000001494CE09A40> for n in fib(6): print(n)
Summary: The generator may be used
[]
oryield
, the addition of a iterables (generator)Iterator
In front of the generator when speaking, we have a
next()
function. Iterator is defined by its past.It can be next () function call, and returns the next target value continuously referred iterator.
Speaking in front of iteration time, we talked about, if you want to determine whether an object is waiting for the object, there is a
isinstance()
function.Iterator data type name is:
Iterator
, iterator is equivalent to a data stream.from collections import Iterator print(isinstance((x for x in range(10)), Iterator)) # 生成器是 print(isinstance([1,2,3], Iterator)) # 列表不是 print(isinstance({"a":1, "b":2}, Iterator)) # 字典不是 print(isinstance('abc', Iterator)) # 字符串不是
Some students might ask, lists, dictionaries, strings are iterables, why not iterators.
This is because the iterator is a representation of the data stream . Because it can be
next()
invoked function and continue to return next data.It can be an iterative iterator object becomes, through
iter()
the function.L = [1,2,3,4,5] a = iter(L) print(next(a)) # output:1 print(next(a)) # output:2 print(next(a)) # output:3
Summary: The two basic methods iterator
iter()
,next()
.