30 lines of Python minimalist code, 10 minutes of common get skills

Programmer Xiaoba 2022-06-23 18:09:03 阅读数:329

linespythonminimalistcodeminutes

learn Python What's the fastest way , Of course, it's all kinds of small projects , Only to think and write , Just remember the rules . This article is about 30 It's a minimalist task , Beginners can try to achieve their own ; This article is also 30 Segment code ,Python Developers can also see if there are unexpected uses .

Python It is the most widely used programming language for machine learning , Its most important advantage lies in the programming Ease of use .

If the reader is right about the basic Python There is already some understanding of grammar , So this article may give you some inspiration . The author gives a brief overview of 30 Segment code , They are usually very practical skills , We can go through it in a few minutes .

1 Repeat element determination

The following methods can check whether there are duplicate elements in a given list , It will use set() Function to move Except for all repeating elements .

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

2 Character element composition determination

Check whether the constituent elements of two strings are the same .

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

3 Memory footprint

import sysvariable = 30print(sys.getsizeof(variable)) # 24

4 Byte usage

The following code block can check the number of bytes occupied by the string .

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

5 Print N Substring

This code block does not need a loop statement to print N Substring .

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

6 Capitalize the first letter

The following code blocks will use title() Method , So the first letter of each word in the uppercase string .

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

7 Block

Given a specific size , Define a function to cut the list by this size .

from math import ceildef chunk(lst, size):return list(map(lambda x: lst[x * size:x * size + size],list(range(0, ceil(len(lst) / size)))))chunk([1,2,3,4,5],2)# [[1,2],[3,4],5]

8 Compress

this Methods to remove Boolean values , for example (False,None,0,“”), It USES filter() function .

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

9 Unpack

The following code snippet can unpack the packed pair list into two different tuples .

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

10 Chain comparison

We can use different operators to compare different elements in a single line of code .

a = 3print( 2 < a < 8) # Trueprint(1 == a < 2) # False

11 Comma connection

The following code can concatenate the list into a single string , And each element is separated by commas .

hobbies = ["basketball", "football", "swimming"]print("My hobbies are: " + ", ".join(hobbies))# My hobbies are: basketball, football, swimming

12 Vowel Statistics

The following method will count the vowels in the string (‘a’, ‘e’, ‘i’, ‘o’, ‘u’) The number of , It's done through regular expressions .

import redef count_vowels(str):return len(len(re.findall(r'[aeiou]', str, re.IGNORECASE)))count_vowels('foobar') # 3count_vowels('gym') # 0

13 Initial lowercase

The following method unifies the first character of a given string to lowercase .

def decapitalize(string):return str[:1].lower() + str[1:]decapitalize('FooBar') # 'fooBar'decapitalize('FooBar') # 'fooBar'

14 Expand the list

This method will recursively expand the nesting of lists into a single list .

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 Poor list

This method will return the elements of the first list , It's not in the second list . If you want to feedback the unique elements of the second list at the same time , One more sentence is needed set_b.difference(set_a).

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 Take the difference through the function

The following method first applies a given function , Then return the list elements with different results after applying the function .

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 Chain function call

You can call multiple functions in one line of code .

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 duplicates

The following code will check the two lists for duplicate items .

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

19 Merge two dictionaries

The following method will 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 once from breturn ca={'x':1,'y':2}b={'y':3,'z':4}print(merge_two_dicts(a,b))#{'y':3,'x':1,'z':4}

stay Python 3.5 Or later , We can also merge dictionaries 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))# {'y': 3, 'x': 1, 'z': 4}

20 Turn the two lists into dictionaries

The following method will turn the two lists into a single 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 enumeration

We often use For Loop through a list , We can also enumerate the indexes and values of a list .

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)

22 execution time

The following code blocks can be used to calculate the time spent executing specific 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

We are using try/except You can also add a else Clause , If there is no trigger error , This clause will be run .

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

24 Element frequency

The following method will take the most common elements in the list according to the element frequency .

def most_frequent(list):return max(set(list), key = list.count)list = [1,2,1,2,3,2,1,4,2]most_frequent(list)

25 Palindrome sequence

The following method checks whether the given string is a palindrome sequence , It first converts all the letters into lowercase , And remove the non alphabetic symbols . Last , It compares the string with the reverse string for equality , Equality is expressed as palindrome sequence .

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

26 Don't use if-else Calculators of

This code can add, subtract, multiply and divide without using conditional statements 、 Exponentiation operation , It is realized through the data structure of dictionary :

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

27 Shuffle

The algorithm will disrupt the order of the list elements , It mainly goes through Fisher-Yates The algorithm sorts the new list :

from copy import deepcopyfrom random import randintdef shuffle(lst):temp_lst = deepcopy(lst)m = len(temp_lst)while (m):m -= 1i = randint(0, m)temp_lst[m], temp_lst[i] = temp_lst[i], temp_lst[m]return temp_lstfoo = [1,2,3]shuffle(foo) # [2,3,1] , foo = [1,2,3]

28 Expand the list

Add all elements in the list , Include sublist , All expanded into a list .

def spread(arg):ret = []for i in arg:if isinstance(i, list):ret.extend(i)else:ret.append(i)return retspread([1,2,3,[4,5,6],[7],8,9]) # [1,2,3,4,5,6,7,8,9]

29 Exchange value

You can exchange the values of two variables without additional operations .

def swap(a, b):return b, aa, b = -1, 14swap(a, b) # (14, -1)spread([1,2,3,[4,5,6],[7],8,9]) # [1,2,3,4,5,6,7,8,9]

30 Dictionary default value

adopt Key Take the corresponding Value value , You can set the default values in the following ways . If get() Method does not set a default value , So if you meet someone who doesn't exist Key, Will return None.

d = {
'a': 1, 'b': 2}print(d.get('c', 3)) # 3

10 Minutes after reading this article , Master common skills !

版权声明:本文为[Programmer Xiaoba]所创,转载请带上原文链接,感谢。 https://pythonmana.com/2022/174/202206231653243766.html