Python is a beautiful shortcode that you can learn in 30 seconds, netizens: It's so easy to use it to cry

Today I will bring you some code snippets that can be learned in 30 seconds. These codes have unlimited potential, contain rich python programming thinking, have a wide range of applications, and are very easy to learn.

1. "Two-dimensional list"

Interpretation: According to the given length and width, and the initial value, return a two-dimensional list.

def initialize_2d_list(w, h, val=None):
    return [[val for x in range(w)] for y in range(h)]

 

Example:

>>> initialize_2d_list(2,2)
[[None, None], [None, None]]

>>> initialize_2d_list(2,2,0)
[[0, 0], [0, 0]]

 

2. Function cutting array

Interpretation: Use a function to apply to each element of an array, so that the array is cut into two parts. If the value returned by the function applied to the element is True, the element is cut into the first part, otherwise it is divided into the second part.

def bifurcate_by(lst, fn):
    return [
      [x for x in lst if fn(x)],
      [x for x in lst if not fn(x)]
    ]

Example:

>>> bifurcate_by(['beep', 'boop', 'foo', 'bar'], lambda x: x[0] == 'b')
[['beep', 'boop', 'bar'], ['foo']]

 

3. "Intersection Point"

Interpretation: After two arrays are applied by a function, the original elements of the common elements are extracted from the first array to form a new array.

def intersection_by(a, b, fn):
    _b = set(map(fn, b))
    return [item for item in a if fn(item) in _b]

Example:

>>> from math import floor
>>> intersection_by([2.1, 1.2], [2.3, 3.4],floor)
[2.1]

 

4. Maximum subscript

Interpretation: Returns the subscript of the maximum value in the array.

def max_element_index(arr):
    return arr.index(max(arr))

Example:

>>> max_element_index([5, 8, 9, 7, 10, 3, 0])
4

 

5. Array symmetry difference

Interpretation: Find out the different elements in the two arrays and combine them into a new array.

def symmetric_difference(a, b):
    _a, _b = set(a), set(b)
    return [item for item in a if item not in _b] + [item for item in b if item not in _a]

Example:

>>> symmetric_difference([1, 2, 3], [1, 2, 4])
[3, 4]

Many people learn python and don't know where to start.
Many people learn python and after mastering the basic grammar, they don't know where to find cases to get started.
Many people who have done case studies do not know how to learn more advanced knowledge.
So for these three types of people, I will provide you with a good learning platform, free to receive video tutorials, e-books, and the source code of the course!
QQ group: 705933274

6. "Number of Clips"

Interpretation: If num is in a range of numbers, return num, otherwise return the boundary closest to this range:

def clamp_number(num,a,b):
    return max(min(num, max(a,b)),min(a,b))

Example:

>> clamp_number(2,3,10)
3

>> clamp_number(7,3,10)
7

>> clamp_number(124,3,10)
10

7. Key-value mapping

Interpretation: Use the object's key to recreate the object, and run a function to create a value for each object's key.
Use dict.keys() to traverse the keys of the object and generate a new value through the function.

def map_values(obj, fn):
    ret = {}
    for key in obj.keys():
        ret[key] = fn(obj[key])
    return ret


Example:

>>> users = {
...   'fred': { 'user': 'fred', 'age': 40 },
...   'pebbles': { 'user': 'pebbles', 'age': 1 }
... }

>>> map_values(users, lambda u : u['age'])
{'fred': 40, 'pebbles': 1}

>>> map_values(users, lambda u : u['age']+1)
{'fred': 41, 'pebbles': 2}

 

8. Case conversion

Interpretation: Change the capitalization of the first letter of English words to lowercase.
upper_rest parameter: Set whether to convert uppercase and lowercase letters except for the first letter.

def decapitalize(s, upper_rest=False):
    return s[:1].lower() + (s[1:].upper() if upper_rest else s[1:])

 

Example:

>>> decapitalize('FooBar')
'fooBar'

>>> decapitalize('FooBar', True)
'fOOBAR'

 

9. Sum at the same time

Interpretation: Sum the objects with the same key value in each dictionary in the list.

def sum_by(lst, fn):
    return sum(map(fn,lst))

Example:

>>> sum_by([{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }], lambda v : v['n'])
14

10. Find the number of occurrences in a line of code

Interpretation: Find the sum of the number of occurrences of a certain number in the list.

def count_occurrences(lst, val):
    return len([x for x in lst if x == val and type(x) == type(val)])

Example:

>>> count_occurrences([1, 1, 2, 1, 2, 3], 1)
3

 

11. Array regrouping

To subdivide a list according to the required size:

The effect is as follows:

chunk([1,2,3,4,5],2)
# [[1,2],[3,4],5]

 

In return, the second parameter of map is a list. Map will use each element in the list to call the function function of the first parameter, and return a new list containing the return value of each function function.

12. Number to array

The same is an application of map, which splits the integer numbers into an array:

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

 

The effect is as follows:

digitize(123)
# [1, 2, 3]

After it converts the integer number n into a string, it also automatically serializes the string, and finally applies the element to the first parameter of the map, converts it into an integer, and returns.

13. 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, the efficiency is very low, we use a non-recursive way to achieve:

The effect is as follows:

fibonacci(7)
# [0, 1, 1, 2, 3, 5, 8, 13]

 

It's very simple to look at it this way, but the thinking has to get around.

14. Underlined string

Batch uniform variable name or string format.

The effect is as follows:

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"


re.sub is used to replace matches in a string. This is actually a "mock doll" usage. It may not be easy to understand at the beginning, and it needs to be understood slowly.

The first replacement is to use ''replace'-' in the s string.

The second replacement is for the string after the first replacement, and replace the character segment (words in all capitals) that meets the regular expression of'([AZ]+)' with r'\1', that is, use A space separates each word.

The third replacement is for the string after the second replacement, and for the character segment that conforms to the regular expression of'([AZ][az]+)' (that is, the first letter is capitalized, the other letters are lowercase) The replacement of r'\1' also separates words with spaces.

I still want to recommend the Python learning group I built myself : 705933274. The group is all learning Python. If you want to learn or are learning Python, you are welcome to join. Everyone is a software development party and share dry goods from time to time (only Python software development related), including a copy of the latest Python advanced materials and zero-based teaching compiled by myself in 2021. Welcome friends who are in advanced and interested in Python to join!

 

Guess you like

Origin blog.csdn.net/pyjishu/article/details/115004500