## Master some advanced usage of Python in 30 seconds, which makes others envy it

Python cola 2021-08-09 17:12:31
master advanced usage python seconds

# 1. The array is then grouped

Subdivide a list according to the required size ：

The effect is as follows ：

``````EXAMPLES
chunk([1,2,3,4,5],2)# [[1,2],[3,4],5]
Copy code ``````

return in ,map The second argument to is a list ,map Each element in the list is used to call the first parameter function function , Return contain every time function The function returns a new list of values .

# 2. Number to array

It's also about map Application , Split the integer number into an array ：

``````def digitize(n):
return list(map(int, str(n)))
Copy code ``````

The effect is as follows ：

``````EXAMPLES
digitize(123)# [1, 2, 3]
Copy code ``````

It will shape the number n After converting to a string , The string is also serialized and segmented automatically , Finally, apply the element to map In the first parameter of , After conversion to shaping, return .

# 3. Non recursive Fibonacci

Remember the Fibonacci sequence , The sum of the first two numbers is the value of the third number , Such as 0、1、1、2、3、5、8、13....

If you use recursion to implement this algorithm , Very inefficient , We implement... In a non recursive way ：

The effect is as follows ：

``````EXAMPLES
fibonacci(7)# [0, 1, 1, 2, 3, 5, 8, 13]
Copy code ``````

This is very simple , But thinking should be able to go around .

# 4. Underlined string

Batch unified variable name or string format .

The effect is as follows ：

``````EXAMPLES
snake('camelCase')# 'camel_case'
snake('some text')# 'some_text'
snake('some-mixed_string With spaces_underscores-and-hyphens')# 'some_mixed_string_with_spaces_underscores_and_hyphens'
snake('AllThe-small Things')# "all_the_small_things"
Copy code ``````

re.sub Used to replace matches in strings . This is actually a “ Dolls ” usage , It may not be easy to understand at first , It needs to be understood slowly .

The first replacement , Yes, it will s In a string , Use ' ' Replace '-'.

Second replacement , Is for the first replaced string , Compliance '([A-Z]+)' The character section of a regular expression （ All capitalized words ） use r' \1' Replace , That is to distinguish each word with a space .

Third replacement , Is the second replaced string , Compliance '([A-Z][a-z]+)' The character section of a regular expression （ That is, the initial letter is capitalized , Other lowercase words ） use r' \1' Replace , Also separate words with spaces .

https://pythonmana.com/2021/08/20210809170413538f.html