In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
What are the practical Python code snippets? for this problem, this article introduces the corresponding analysis and solution in detail, hoping to help more partners who want to solve this problem to find a more simple and feasible method.
Many people use Python in the fields of data science, machine learning, web development, scripting, and automation. It is a very popular language.
Part of the reason for the popularity of Python is that it is easy to learn.
This article will briefly introduce 30 short code snippets that can be mastered in less than 30 seconds.
1. Uniqueness
The following method checks whether there are any duplicates in a given list, which can be removed from the list by the property of set ().
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。 Transposed words (words with the same letter and out of order)
This method can be used to check whether two strings are indexers.
From collections import Counter def anagram (first, second): return Counter (first) = = Counter (second) anagram ("abcd3", "3acdb") # True
3. Memory
This 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
This method outputs the byte size of the string.
Def byte_size (string): return (len (string.encode ('utf-8') byte_size ('') # 4 byte_size ('Hello World') # 11
5. Print a string N times
This code snippet can print strings multiple times without going through a loop.
N = 2; s = "Programming"; print (s * n); # ProgrammingProgramming
6. Initials are capitalized
The following code snippet capitalizes the first letter of each word in the string using only title ().
S = "programming is awesome" print (s.title ()) # Programming Is Awesome
7. List subdivision
This method subdivides the list into lists of specific sizes.
Def chunk (list, size): return [list [I: i+size] for i in range (0meme Len (list), size)]
8. Compress
The following code uses filter () to remove the error values (False, None, 0, and "") from the list.
Def compact (lst): return list (filter (bool, lst)) compact ([0,1, False, 2,', 3, 'axiom,' Aguilar, 34]) # [1, 2, 3, 'axiang,' aforementioned, 34]
9. Count
The following code can be used to swap 2D array arrangements.
Array = [['averse,' b'], ['centering,' d'], ['eBay,' f']] transposed = zip (* array) print (transposed) # [('axiang,' censor,'e'), ('baked,' dumped,'f')]
10. Chain comparison
The following code compares the various operators multiple times.
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 ret def deep_flatten(lst): result = [] result.extend( spread(list(map(lambda x: deep_flatten(x) if type(x) == list else x, lst)))) return result deep_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 floor difference_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 + b def subtract(a, b): return a – b a, b = 4, 5 print((subtract if a >B else add) (a, b)) # 9
18. Whether the duplicate value exists or not
The following method uses the property that set () contains only unique elements to check for duplicate values in the list.
Def has_duplicates (lst): return len (lst)! = len (set (lst)) x = [1, True has_duplicates, 3, 4, 5] y = [1, 2, 3, 5] has_duplicates (x) # True has_duplicates (y) # False
19. Merge font
The following method merges two fonts.
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 c a = {"x": 1, "y": 2} b = {"y": 3, "z": 4} print (merge_two_dicts (a, b)) # {"y": 3, "x": 1, "z": 4}
In Python3.5 and upgrade, the step code can also be executed in the following ways:
Def merge_dictionaries (a, b) return {* * a, * * b} a = {"x": 1, "y": 2} b = {"y": 3,'z ": 4} print (merge_dictionaries (a, b)) # {" x ": 3," x: 1, "z: 4}
20. Convert two lists to font
The following method converts two lists to a font.
Def to_dictionary (keys, values): return dict (zip (keys, values)) keys = ["a", "b", "c"] values = [2,3,4] print (to_dictionary (keys, values)) # {'averse: 2,' cession: 4, 'baked: 3}
21. Enumerate
The following code snippet can be enumerated to get the values and indexes of the list.
List = ["a", "b", "c", "d"] for index, element in enumerate (list): print ("Value", element, "Index", index,) # ('Value',' asides, 'Index', 0) # ('Value',' baked, 'Index', 1) # ('Value',' cations, 'Index', 2) # ('Value',' dudes, 'Index', 3)
twenty-two。 Time cost
The following code calculates the time required to execute a particular code.
Import time start_time = time.time () a = 1b = 2c = a + b print (c) # 3 end_time = time.time () total_time = end_time-start_time print ("Time:", total_time) # ('Time:', 1.1205673217773438e-05)
23. Try else statement
The else sentence can be used as part of the try/except statement, and if there is no exception, the else statement is executed.
Try: 2: 3 except TypeError: print ("An exception was raised") else: print ("Thank God, no exceptions were raised.") # Thank God, no exceptions were raised.
24. Elements with a high frequency of occurrence
This method outputs the highly visible elements in the list.
Def most_frequent (list): return max (set (list), key = list.count) list = [most_frequent (list)
25. Palindromes (read the same string in front and back)
The following code checks whether the given string is a palindrome. First convert the string to lowercase, then remove non-alphabetic characters from it, and finally compare the new string version with the original version.
Def palindrome (string): from re import sub s = sub ('[\ W_]','', string.lower ()) return s = s [::-1] palindrome ('taco cat') # True
twenty-six。 Calculators that do not use if-else statements
The following code snippet shows how to write a simple calculator without using if-else conditional statements.
Import operator action = {"+": operator.add, "-": operator.sub, "/": operator.truediv, "*": operator.mul, "*": pow} print (action ['-'] (50,25)) # 25
twenty-seven。 Random ordering
The algorithm uses Fisher-Yates algorithm to sort the elements in the new list randomly.
From copy import deepcopy from random import randint def 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。 Expand the list
This method will be similar to []. Concat (… in javascript. Arr) such a list is expanded.
Def spread (arg): ret = [] for i in arg: if isinstance (I, list): ret.extend (I) else: ret.append (I) return ret spread
twenty-nine。 Exchange variable
This method allows you to quickly exchange two variables without using additional variables.
Def swap (a, b): return b, an a, b =-1,14 swap (a, b) # (14,-1)
thirty。 Get the default value of the missing part
The following code gets the default value if the desired object is not in the font.
D = {'averse: 1,' baked: 2} print (d.get ('cations, 3)) # 3
Here are only some methods that can help us in our daily work.
The answers to the questions about the practical Python code snippets are shared here. I hope the above content can be of some help to you. If you still have a lot of doubts to be solved, you can follow the industry information channel to learn more about it.
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.