Public account: You and the cabin by: Peter Editor: Peter

Hello, I’m Peter

Python is known for its syntax brevity. As we’ve learned Python, we’ve always found that Python can help us solve a lot of problems very easily.

Sometimes seemingly complex tasks can be done with even a single line of Python code.

Here is Peter’s introduction to 40 interesting and useful Python code lines. Let’s see how Python can be powerful

Print hello python

Everyone starts with the print function

print("hello python")  
Copy the code
hello python
Copy the code
print("hello Peter")  
Copy the code
hello Peter
Copy the code
print("Data analyst")  
Copy the code
Data analystCopy the code

Binary to decimal

int("01110".2)  # 2 ^ 3 ^ 2 + 2 + 2
Copy the code
14
Copy the code

Convert octal to decimal

int("140".8)  
Copy the code
96
Copy the code

Conversion from hexadecimal to decimal

int("ac1".16)
Copy the code
2753
Copy the code

Generates a list of consecutive values

list(range(9))
Copy the code
[0, 1, 2, 3, 4, 5, 6, 7, 8]
Copy the code

Gauss sum

One line of code to solve the Gauss sum: Solve for the sum of all numbers from 1 to 100

sum(range(1.101))  The # range function does not contain 101
Copy the code
5050
Copy the code

Find the sum of odd and even numbers

# divided by 2 has a remainder of 0 which is even

sum(i for i in range(1.101) if i % 2= =0)  
Copy the code
2550
Copy the code
# divided by 2 without a remainder of 0 is odd

sum(i for i in range(1.101) if i % 2! =0)  
Copy the code
2500
Copy the code

factorial

import math  Need to use a third party library

math.factorial(6) # 6 * 5 * 4 * 3 * 2 * 1
Copy the code
720
Copy the code

Matrix transpose

Matrix transpose is the transformation of rows and columns of a matrix

list1 = [[1.4.7], [2.5.8], [3.6.9]]  Define a nested list
Copy the code
list(list(x) for x in zip(*list1))  # list function implementation
Copy the code
[2, 3], [4, 5, 6], [7, 8, 9]]Copy the code
[list(x) for x in zip(*list1)]   # [] symbol implementation
Copy the code
[2, 3], [4, 5, 6], [7, 8, 9]]Copy the code
for x in zip(*list1):
    print(list(x))
Copy the code
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
Copy the code

Nested list merge

Combine multiple lists into one large list

list4 = [[1.2.3], [4.5.6], [7.8.9]]  Define a list

list(item for list5 in list4 for item in list5) # From big to small
Copy the code
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Copy the code

List of merger

a = [1.2.3]
b = [4.5.6]

a.extend(b)
Copy the code
a
Copy the code
[1, 2, 3, 4, 5, 6]
Copy the code

A list of reverse

list6 = [1.2.3.4.5.6.7]

list6[::-1]
Copy the code
[7, 6, 5, 4, 3, 2, 1]
Copy the code

The list of unpacked

h,*i,j = [1.2.3.4.5]

print(h)
print(i)
print(j)
Copy the code
1
[2, 3, 4]
5
Copy the code

List to heavy

By turning a list into a set, we can take advantage of the de-weighting property of a set and then turn it into a list

list7 = [1.2.3.4.3.2.3.3]

list(set(list7))
Copy the code
[1, 2, 3, 4]
Copy the code

A list of filters

The filter function takes two arguments:

  • Specify a function
  • Iterable objects to be executed, each of which performs the previous function
list(filter(lambda x:x % 3= =0[1.3.6.7.9.10]))  # Find multiples of 3
Copy the code
[3, 6, 9]
Copy the code

List derivation

[number for number in range(0.11)]  # []
Copy the code
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Copy the code

Set derivation

{number for number in range(0.11)}  # {}
Copy the code
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
Copy the code

Merge collection

s1 = {1.2.3}
s2 = {4.5.6}

s1.update(s2)
Copy the code
s1
Copy the code
{1, 2, 3, 4, 5, 6}
Copy the code

Dictionary derivation

{i:i**3 for i in range(0.5)}  # I **3 means I to the third power
Copy the code
{0: 0, 1: 1, 2: 8, 3: 27, 4: 64}
Copy the code

Merge the dictionary

d1 = {"name1":"xiaoming"."age1": 19}
d2 = {"name2":"xiaoming"."age2": 28}

d1.update(d2)
Copy the code
d1
Copy the code
{'name1': 'xiaoming', 'age1': 19, 'name2': 'xiaoming', 'age2': 28}
Copy the code

if-for

# Find multiples of 3

[number for number in range(0.20) if number % 3= =0] 
Copy the code
[0, 3, 6, 9, 12, 15, 18]
Copy the code

if-else

print("Even") if 8 % 2= =0 else ("Odd")
Copy the code
An even numberCopy the code
print("Even") if 9 % 2= =0 else print("Odd")
Copy the code
An odd numberCopy the code

Quick sort

list2 = [9.5.1.6.2.8]  Define a list

sorted(list2) # default ascending order
Copy the code
[1, 2, 5, 6, 8, 9]
Copy the code
sorted(list2, reverse=True) # descending
Copy the code
[9, 8, 6, 5, 2, 1]
Copy the code
list3 = ["ac"."ab"."bb"."aa"."bc"."cd"."ca"]
sorted(list3)
Copy the code
['aa', 'ab', 'ac', 'bb', 'bc', 'ca', 'cd']
Copy the code

First we sort by the ASCII value of the first letter, which is ascending by default. A minimum. When the first letter is the same, sort by the second letter

The string is converted to bytes

"string to bytes".encode()
Copy the code
b'string to bytes'
Copy the code

Get 26 alphabets

import string

string.ascii_letters  # case
Copy the code
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
Copy the code

Get uppercase alphabet

string.ascii_uppercase
Copy the code
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
Copy the code

Get lowercase alphabet

string.ascii_lowercase
Copy the code
'abcdefghijklmnopqrstuvwxyz'
Copy the code

String case conversion

"Hello! My name is Peter".lower()   # convert to lowercase
Copy the code
'hello! my name is peter'
Copy the code
Another way to write # to lowercase

"Hello! My name is Peter".casefold()  
Copy the code
'hello! my name is peter'
Copy the code
"Hello! My name is Peter".upper()  # convert to all uppercase
Copy the code
'HELLO! MY NAME IS PETER'
Copy the code
"Hello! My name is Peter".title()  # capitalize
Copy the code
'Hello! My Name Is Peter'
Copy the code

Finding the longest string

list7 = ["c"."html"."javascript"."java"]

max(list7, key=len)  The # key argument specifies the function
Copy the code
'javascript'
Copy the code
max(list7)  # the default
Copy the code
'javascript'
Copy the code

Deletes a number from a string

"".join(list(filter(lambda x: x.isalpha(), "abcde12hk18")))
Copy the code
'abcdehk'
Copy the code
list(filter(lambda x: x.isalpha(), "abcde12hk18"))
Copy the code
['a', 'b', 'c', 'd', 'e', 'h', 'k']
Copy the code

Strings in lists become numeric values

list(map(int["10"."90"."50"]))
Copy the code
[10, 90, 50]
Copy the code

String inversion

"python"[: : -1]
Copy the code
'nohtyp'
Copy the code

Switching variable

a, b = 5.8  # Define two variables
Copy the code
print("Pre-exchange A :",a)
print("Pre-exchange B :",b)
Copy the code
A: 5 before exchange B: 8 before exchangeCopy the code
a, b = b, a  # Exchange one line of code
Copy the code
print("After the exchange A :",a)
print("After exchange B :",b)
Copy the code
After the exchange, A: 8 b: 5Copy the code

Data type checking

isinstance(5.int)  # numerical
Copy the code
True
Copy the code
isinstance("python".int)
Copy the code
False
Copy the code
isinstance("python".str)  # string
Copy the code
True
Copy the code
isinstance([1.3.6].list)  # list
Copy the code
True
Copy the code

Fibonacci numbers

fibo = lambda x: x if x <= 1 else fibo(x-1) + fibo(x-2) 

fibo(10)
Copy the code
55
Copy the code

Word frequency statistics

Counts the number of single characters in a string

"javascript".count("a")
Copy the code
2
Copy the code
"javascript".count("s")
Copy the code
1
Copy the code
"hello".count("l")
Copy the code
2
Copy the code

Count the number of list elements

import pandas as pd

list10 = [1.3.4.6.1.2.3.1.1.2.5.6.2]

pd.value_counts(list10)
Copy the code
1    4
2    3
3    2
6    2
4    1
5    1
dtype: int64
Copy the code

Count the number of string elements

from collections import Counter

Counter("abcdeabcdabcaba")
Copy the code
Counter({'a': 5, 'b': 4, 'c': 3, 'd': 2, 'e': 1})
Copy the code

Most statistical element

list10 = [1.3.4.6.1.2.3.1.1.2.4.6.2]

max(list10, key=list10.count)  # element 1 at most
Copy the code
1
Copy the code
min(list10, key=list10.count)  Element 3 is the fewest, appearing only once
Copy the code
3
Copy the code

The current time

import time

time.time()   # timestamp form
Copy the code
1632501677.992713
Copy the code
time.ctime()  # Standard form
Copy the code
'Sat Sep 25 00:41:18 2021'
Copy the code