Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to write Python code quickly

2025-01-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article focuses on "how to write Python code quickly". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Now let the editor take you to learn how to write Python code quickly.

1. "2D list"

Interpretation: returns a two-dimensional list based on the given length and width, as well as the initial value.

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

Example:

> initialize_2d_list (2Jue 2) [[None, None], [None, None] > initialize_2d_list (2Jing 2 Jing 0) [[0,0], [0,0]] 2. Function cut 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 to 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"

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 an 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]) 45. Array symmetry error

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

Def symmetric_difference (a, b): _ a, _ b = set (a), set (b) return [item for item in an 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] 6. "number of clips"

Interpretation: if num falls within a range of numbers, return num, otherwise return the boundary closest to that range:

Def clamp_number (num,a,b): return max (min (num, max (aMaginb)), min (aMaginb))

Example:

> > clamp_number (2 and 3) > > clamp_number (7) > clamp_number (124). Key-value mapping

Interpretation: recreate the object using the object's key and run the function to create a value for each object's key.

Use dict.keys () to iterate through the object's key 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 first letter of English words from uppercase to lowercase.

Upper_rest parameter: sets whether to convert the case of letters other than 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.

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']) 1410. One line of code asks for the number of occurrences.

Interpretation: find out the sum of the number of occurrences 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) 311. Array re-grouping

Subdivide a list according to the desired size:

The effect is as follows:

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

In return, the second argument to map is a list, and map uses each element in the list to call the function function of the first parameter, returning a new list of values returned by each function function.

twelve。 Digital rotation array

It is also an application about map that splits shaping numbers into arrays:

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

The effect is as follows:

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

After it converts the integer n to a string, it automatically serializes and splits the string, and finally applies the element to the first parameter of map, which is converted to plastic and returned.

13. Non-recursive Fibonacci

Remember the Fibonaccine 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 we use recursion to implement this algorithm, it is very inefficient, so we implement it in a non-recursive way:

The effect is as follows:

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

It is very simple to look at it this way, but the mind has to come around.

14. Underline a 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 "nesting doll" usage, which may not be easy to understand at first and needs to be understood slowly.

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

The second replacement, for the first replaced string, replaces the character segments (all uppercase words) that match the'([Amurz] +) 'regular expression with r'\ 1', that is, distinguishing each word with a space.

The third replacement is to replace the second replaced string with r'\ 1' for the character segments (that is, words with uppercase first letters and other lowercase letters) that match the'([Amurz] [a murz] +) 'regular expression, which is to separate the words with spaces.

At this point, I believe you have a deeper understanding of "how to write Python code quickly". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report