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 30 pieces of Python practical code that you can learn and use

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

Share

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

That is to learn how to write 30 pieces of Python practical code, in view of this problem, this article introduces the corresponding analysis and solutions in detail, hoping to help more partners who want to solve this problem to find a more simple and feasible method.

Python is one of the most popular languages at present, and it is widely used by many people in data science, machine learning, web development, scripting and automation. Its simplicity and ease of use make it widely sought after.

In this Python tutorial, we will introduce 30 short code snippets that you can understand and learn in 30 seconds or less.

1. Check for duplicate elements

The following method checks whether there are duplicate elements in a given list. It uses the set () attribute, which removes duplicate elements from the list.

Def all_unique (lst): return len (lst) = = len (set (lst)) x = [1, False all_unique, 2, 2, 3, 3, 3, 4, 5] y = [1, 2, 3, 5] all_unique (x) # False all_unique (y) # True

two。 Transpositional words

Detect whether two strings are positional words for each other (that is, reverse the order of characters)

From collections import Counter def anagram (first, second): return Counter (first) = = Counter (second) anagram ("abcd3", "3acdb") # True

3. Check memory usage

The following code snippet can be used to check the memory usage of an object.

Import sys variable = 30 print (sys.getsizeof (variable)) # 24

4. Byte size calculation

The following method returns the string length in bytes.

Def byte_size (string): return (len (string.encode (utf-8) byte_size () # 4 byte_size (Hello World) # 11

5. Print the string repeatedly N times

The following code prints a string n times without using a loop

N = 2; s = "Programming"; print (s * n); # ProgrammingProgramming

6. Initials are capitalized

The following code snippet capitalizes each word in the string using the title () method.

S = "programming is awesome" print (s.title ()) # Programming Is Awesome

7. Divide into blocks

The following method uses range () to block the list into smaller lists of the specified size.

From math import ceil def chunk (lst, size): return list (map (lambda x: lst [x * size:x * size + size], list (range (0, ceil (len (lst) / size) chunk)

8. Compress

The following method uses fliter () to delete error values from the list (such as: False, None, 0 and ")

Def compact (lst): return list (filter (bool, lst)) compact ([0,1, False, 2, 3, a, s, 34]) # [1,2,3, a, s, 34]

9. Interval number

The following code snippet can be used to convert a 2D array.

Array = [[a, b], [c, d], [e, f]] transposed = zip (* array) print (transposed) # [(a, c, e), (b, d, f)]

10. Chain comparison

The following code can be compared multiple times in one line with various operators.

A = 3 print (2

< a < 8) # True print(1 == a < 2) # False 11.逗号分隔 以下代码段可将字符串列表转换为单个字符串,列表中的每个元素用逗号分隔。 hobbies = ["basketball", "football", "swimming"]print("My hobbies are: " + ", ".join(hobbies)) # My hobbies are: basketball, football, swimming 12.计算元音字母数 以下方法可计算字符串中元音字母('a', 'e', 'i', 'o', 'u')的数目。 import re def count_vowels(str): return len(len(re.findall(r [aeiou] , str, re.IGNORECASE))) count_vowels( foobar ) # 3 count_vowels( gym ) # 0 13.首字母恢复小写 以下方法可用于将给定字符串的第一个字母转换为小写。 def decapitalize(string): return str[:1].lower() + str[1:] decapitalize( FooBar ) # fooBar decapitalize( FooBar ) # fooBar 14.平面化 以下方法使用递归来展开潜在的深度列表。 def spread(arg): ret = [] for i in arg: if isinstance(i, list): ret.extend(i) else: ret.append(i) return retdef deep_flatten(lst): result = [] result.extend( spread(list(map(lambda x: deep_flatten(x) if type(x) == list else x, lst)))) return resultdeep_flatten([1, [2], [[3], 4], 5]) # [1,2,3,4,5] 15.差异 该方法只保留第一个迭代器中的值,从而发现两个迭代器之间的差异。 def difference(a, b): set_a = set(a) set_b = set(b) comparison = set_a.difference(set_b) return list(comparison)difference([1,2,3], [1,2,4]) # [3] 16.寻找差异 下面的方法在将给定的函数应用于两个列表的每个元素后,返回两个列表之间的差值。 def difference_by(a, b, fn): b = set(map(fn, b)) return [item for item in a if fn(item) not in b]from math import floordifference_by([2.1, 1.2], [2.3, 3.4],floor) # [1.2]difference_by([{ x : 2 }, { x : 1 }], [{ x : 1 }], lambda v : v[ x ]) # [ { x: 2 } ] 17.链式函数调用 以下方法可在一行中调用多个函数。 def add(a, b): return a + bdef subtract(a, b): return a - ba, b = 4, 5print((subtract if a >

B else add) (a, b)) # 9

18. Check for duplicate values

The following method uses the set () method to check whether the list has duplicate values by containing only the facts of the unique element.

Def has_duplicates (lst): return len (lst)! = len (set (lst)) x = [1, Truehas_duplicates, 3, 4, 5] y = [1, 2, 3, 5] has_duplicates (x) # Truehas_duplicates (y) # False

19. Merge two dictionaries

The following methods can be used to merge two dictionaries.

Def merge_two_dicts (a, b): C = a.copy () # make a copy of a c.update (b) # modify keys and values of a with the ones from b return ca = {x: 1, y: 2} b = {y: 3, z: 4} print (merge_two_dicts (a, b)) # {y: 3, x: 1, z: 4}

In Python 3.5 and later, you can also do the following:

Def merge_dictionaries (a, b) return {* * a, * * b} a = {x: 1, y: 2} b = {y: 3, z: 4} print (merge_dictionaries (a, b)) # {y: 3, x: 1, z: 4}

20. Convert two lists into a dictionary

The following method converts two lists into a dictionary.

Def to_dictionary (keys, values): return dict (zip (keys, values)) keys = ["a", "b", "c"] values = [2,3,4] print (to_dictionary (keys, values)) # {a: 2, c: 4, b: 3}

21. Use enumerations

The following method takes a dictionary as input and then returns only the keys in that dictionary.

List = ["a", "b", "c", "d"] for index, element in enumerate (list): print ("Value", element, "Index", index,) # (Value, a, Index, 0) # (Value, b, Index, 1) # (Value, c, Index, 2) # (Value, d, Index, 3)

twenty-two。 Calculate the time required

The following code snippet can be used to calculate the time required to execute a particular code.

Import timestart_time = time.time () a = 1b = 2c = a + bprint (c) # 3end_time = time.time () total_time = end_time-start_timeprint ("Time:", total_time) # (Time:, 1.1205673217773438e-05)

23.Try else instruction

You can use the else clause as part of the try/except block and execute it if no exception is thrown.

Try: 2*3except TypeError: print ("An exception was raised") else: print ("Thank God, no exceptions were raised.") # Thank God, no exceptions were raised

24. Find the most common element

The following method returns the most common elements that appear in the list.

Def most_frequent (list): return max (set (list), key = list.count) list = [most_frequent (list)

25. Palindromes

The following method checks whether the given string is a palindrome structure. This method first converts the string to lowercase and then removes non-alphanumeric characters from it. Finally, it compares the new string with the inverted version.

Def palindrome (string): from re import sub s = sub ([W_], string.lower ()) return s = = s [::-1] palindrome (taco cat) # True

twenty-six。 A simple calculator without an if-else statement

The following code snippet shows how to write a simple calculator that does not use if-else conditions.

Import operatoraction = {"+": operator.add, "-": operator.sub, "/": operator.truediv, "*": operator.mul, "* *": pow} print (action [-] (50,25)) # 25

twenty-seven。 Disorder of the order of elements

The following algorithm randomly scrambles the order of the elements in the list by implementing the Fisher-Yates algorithm to sort in the new list.

From copy import deepcopyfrom random import randintdef shuffle (lst): temp_lst = deepcopy (lst) m = len (temp_lst) while (m): M-= 1 I = randint (0, m) temp_lst [m], temp_ LST [I] = temp_lst [I], temp_ LST [m] return temp_lst foo = [1je 2jue 3] shuffle (foo) # [2Jing 3jue 1], foo = [1Jing 2jue 3]

twenty-eight。 List flattening

The following methods flatten the list, similar to []. Concat (… in JavaScript. Arr).

Def spread (arg): ret = [] for i in arg: if isinstance (I, list): ret.extend (I) else: ret.append (I) return retspread

twenty-nine。 Variable exchange

Here is a quick way to exchange two variables without the need for additional variables.

Def swap (a, b): return b, aa, b =-1, 14swap (a, b) # (14,-1)

thirty。 Get the default value of the missing key

The following code snippet shows how to get the default value if the dictionary does not contain the key you are looking for.

D = {a: 1, b: 2} print (d.get (c, 3)) # 3 this is the answer to the question about how to write 30 pieces of Python code that is ready to use. I hope the above content can be of some help to everyone. If you still have a lot of doubts to be solved, you can follow the industry information channel for more related knowledge.

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