Ever since I wrote the first line of code in Python, I have been attracted by its simplicity, excellent readability and particularly popular line of code.
In the following, I will introduce and explain some Python one-line programs.
There may be some you don't know yet, but they are useful for your future Python projects.
Many people learn python and don't know where to start.
Many people learn python and after mastering the basic grammar, they don't know where to find cases to get started.
Many people who have done case studies do not know how to learn more advanced knowledge.
For these three types of people, I will provide you with a good learning platform, free to receive video tutorials, e-books, and course source code! ??¤
QQ group: 232030553
▍1. Exchange two variables
# a = 4 b = 5 a,bb = b,a # print(a,b) >> 5,4
Let's make a simple start by exchanging two variables.
This method is one of the simplest and most intuitive, and can be written without using temporary variables or applying arithmetic operations.
▍2, multiple variable assignment
a,b,c = 4,5.5,'Hello' #print(a,b,c) >> 4,5.5,hello
You can use commas and variables to assign multiple values to variables at once. Using this technique, you can assign multiple data types at once.
You can use lists to assign values to variables. The following is an example of assigning multiple values in the list to a variable.
a,b,*c = [1,2,3,4,5] print(a,b,c) > 1 2 [3,4,5]
▍3, the sum of even numbers in the list
There are many ways to do this, but the best and easiest way is to use the list index and sum function.
a = [1,2,3,4,5,6] s = sum([num for num in a if num%2 == 0]) print(s) >> 12
▍4, delete multiple elements from the list
del is a keyword used in Python to delete values from a list.
#### Deleting all even a = [1,2,3,4,5] from to [1 :: 2] print(a) >[1, 3, 5] a
▍5, read files
lst = [line.strip() for line in open('data.txt')] print(lst)
Here we use the list to deal with.
First, we open a text file and use a for loop to read it line by line. Finally, use strip to remove all unnecessary space.
By using the list function, the code is simpler and shorter.
list(open('data.txt')) ##Using with will also close the file after use with open("data.txt") as f: lst=[line.strip() for line in f] print(lst)
▍6, write data to file
with open("data.txt",'a',newline='\n') as f: f.write("Python is awsome")
The above code first creates a file data.txt (if there is no one), and then it will write Python is awesome in the file.
▍7, create a list
lst = [i for i in range(0,10)] print(lst) > [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] or lst = list(range(0,10)) print(lst)
We can also use the same method to create a list of strings.
lst = [("Hello "+i) for i in ['Karl','Abhay','Zen']] print(lst) > ['Hello Karl', 'Hello Abhay', 'Hello Zen']
▍8, mapping list or type conversion entire list
Sometimes in our project, we need to change the data type of all elements in the list. The first method you think of might be to use a loop, then access all the elements in the list, and then change the data type of the elements one by one.
This method is old school. In Python we have a mapping function that can do this for us.
list(map(int,['1','2','3'])) > [1, 2, 3] list(map(float,[1,2,3])) > [1.0, 2.0, 3.0] [float(i) for i in [1,2,3]] > [1.0, 2.0, 3.0]
▍9, create a collection
The method we used to create lists can also be used to create collections. Let's create a set using the square root method that includes all even numbers in the range.
#### Square of all even numbers in an range {x**2 for x in range(10) if x%2==0} > {0, 4, 16, 36, 64}
▍10、Fizz Buzz
In this test, we need to write a program to print numbers from 1 to 20. But if it is a multiple of 3, print Fizz, if it is a multiple of 5, print Buzz, if it is a multiple of 3 and 5, print FizzBuzz, otherwise print the number.
It seems that we must use loops and multiple if-else statements. If you try to do it in other languages, you may need to write 10 lines of code, but with Python, we can implement FizzBuzz with just one line of code.
['FizzBuzz' if i%3==0 and i%5==0 else 'Fizz' if i%3==0 else 'Buzz' if i%5==0 else i for i in range(1,20)]
In the above code, we use list comprehension to run a loop from 1 to 20, and then in each iteration of the loop, we check whether the number is divisible by 3 or 5. If it is, then we replace the value with Fizz or Buzz, or use the FizzBuzz value.
▍ 1 1. Palindrome
A palindrome is a number or string that looks the same when it is reversed.
text = 'level' ispalindrome = text == text [:: - 1] ispalindrome > True
▍12, the integers separated by spaces to a list
lis = list(map(int, input().split())) print(lis) > 1 2 3 4 5 6 7 8 [1, 2, 3, 4, 5, 6, 7, 8]
▍13, Lambda function
The lambda function is a small anonymous function. The lambda function can accept any number of parameters, but only one expression.
# Function that returns square of any number sqr = lambda x: x * x sqr(10) > 100
▍14, check the existence of numbers in the list
num = 5 if num in [1,2,3,4,5]: print('present') > present
▍15, print pattern
In Python, we only need one line of code to draw amazing patterns.
n = 5 print('\n'.join('' * i for i in range(1, n + 1))) >
▍16, find factorial
The factorial is the product of an integer and all integers below it.
import math n = 6 math.factorial(n) > 720
▍17, Fibonacci sequence
A set of numbers, where each number (Fibonacci number) is the sum of the previous two numbers. The simplest Fibonacci sequence is 1, 1, 2, 3, 5, 8, 13, and so on. You can use list comprehensions and for loops to create Fibonacci numbers in a range.
fibo = [0.1] [fibo.append(fibo[-2]+fibo[-1]) for i in range(5)] fibo > [0, 1, 1, 2, 3, 5, 8]
▍18, prime number
A prime number is a number that can only be divisible by itself and 1. For example: 2, 3, 5, 7, etc. In order to generate prime numbers in a range, we can use the list function with filter and lambda to generate prime numbers.
list(filter(lambda x:all(x % y != 0 for y in range(2, x)), range(2, 13))) > [2, 3, 5, 7, 11]
▍19, find the maximum value
findmax = lambda x,y: x if x > y else y findmax(5,14) > 14 or max(5,14)
In the above code, we use the lambda function to check the comparison condition and based on the maximum value returned.
Or use the max() built-in function.
▍20, linear algebra
Sometimes we need to scale the elements in the list by 2 to 5 times. The following code explains how to do this.
def scale(lst, x): return [i*x for i in lst] scale([2,3,4], 2) > [4,6,8]
▍21, matrix transpose
You need to convert all rows to columns and vice versa. In Python, you can use the zip function to replace a matrix in a line of code.
a=[[1,2,3], [4,5,6], [7,8,9]] transpose = [list(i) for i in zip(*a)] transpose > [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
▍22, counting
This is an important and useful use case when we need to know the number of times a value appears in the text. In Python, there is the re library to help you complete this work.
import re len(re.findall('python','python is a programming language. python is python.')) > 3
▍23, replace text with other text
"python is a programming language.python is python".replace("python",'Java') > Java is a programming language. Java is Java
▍24, simulated coin toss
This may not be that important, but it can be very useful when you need to generate some random choices from a given set of choices.
import random random.choice(['Head',"Tail"]) > Head
▍25, generate group
groups = [(a, b) for a in ['a', 'b'] for b in [1, 2, 3]] groups > [('a', 1), ('a', 2), ('a', 3), ('b', 1), ('b', 2), ('b', 3)]