In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains "what skills Python can write better code", the content of the explanation is simple and clear, easy to learn and understand, the following please follow the editor's ideas slowly in depth, together to study and learn "what skills Python can write better code" bar!
Technique 01-multiple assignment of variables
Python allows us to assign values to multiple variables in a row. You can separate variables with commas. Front-line multitasking has many advantages. It can be used to assign multiple values to multiple variables or to assign multiple values to a single variable name. Let's make a problem statement, where we must assign values 50 and 60 to variables an and b. The general code is as follows.
A = 50 b = 60 print (a) print (type (a)) print (type (b))
Output quantity
50 60
Condition I-value equals variable
When a variable is equal to multiple assignments, each value is stored in all variables.
Print (type (a)) print (type (b))
Output quantity
50 60
The two programs give the same result. This is the benefit of using a row value allocation.
Conditional II- value is greater than variable
Let's try to increase the number of values in the previous program. You can assign multiple values to a single variable. When assigning multiple values to a variable, we must use an asterisk before the variable name.
A, * b = 50,60,70 print (a) print (b) print (type (a)) print (type (b))
Output quantity
50 [60, 70]
The first value is assigned to the first variable. The second variable will collect the value from the given value. This creates a list type object.
Conditional III- multivariable one value
We can assign a value to multiple variables. Each variable will be separated by an equal sign.
A = b = c = 50 print (a meme bjorc) print (type (a)) print (type (b)) print (type (c))
Output quantity
50 50 50
Tip 02-swap two variables
Exchange is the process of exchanging the values of two variables with each other. This can be useful in many operations in computer science. Here, I have written two main methods for programmers to exchange values and the best solution.
Method I-use temporary variables
This method uses temporary variables to store some data. The following code is written using temporary variable names.
A print b = 50,60 print (ameme b) temp= axiom b # averse 50 baked 50 temp=110 b = a # averse 50 baked 50 temp=110 a = temp-b # averse 60 baked 50 temp=110 print ("After swapping:", aPermian b)
Output quantity
50 60 After swapping: 60 50
Method II- does not use temporary variables
The following code swaps variables without using temporary variables.
A print b = 50,60 print (aMagneb) a = aquib # averse 110 baud 60 b = a Mui b # aqu 110 bang 50 a = a Mui b # ahe 60 baked 50 print ("After swapping:", aMagneb)
Output quantity
50 60 After swapping: 60 50
Methods the excellent solution in III-Python
This is another way to exchange variables using python. In the previous section, we learned about multiple assignments. We can use the concept of exchange.
A print b = 50,60 print (a minute b) a print b = b ("After swapping", a line b)
Output quantity
50 60 After swapping 60 50
Tip 03-reverse string
There is another cool technique for reversing strings in python. The concept used to reverse a string is called string slicing. You can reverse any string after the variable name with the symbol [::-1].
My_string = "MY STRING" rev_string = my_string [:-1] print (rev_string)
Output quantity
GNIRTS YM
Tip 04-split words on a line
You don't need a special algorithm to split a word into a line. To do this, we can use the keyword split (). Here, I wrote two ways to segment words.
Method 1-use iteration
My_string = "This is a string in Python" start= 0 end= 0 my_list = [] for x in my_string: end=end+1 if (end'): my_list.append (my_ string [start: end+1]) start=end+1 my_list.append (my_ string [start: end+1]) print (my_list)
Output quantity
['This','is','a', 'string','in', 'Python']
Method II- uses the segmentation function
My_string = "This is a string in Python" my_list = my_string.split ('') print (my_list)
Output quantity
['This','is','a', 'string','in', 'Python']
Tip 05-arrange the list of words in one line
This is the opposite of the previous process. In this section, we will use the join function to convert the word list to a single line. The syntax for using the join function is given below.
Syntax: "" .join (string)
My_list = ['This',' is','a', 'string',' in', 'Python'] my_string = "" .join (my_list)
Output quantity
This is a string in Python
Tip 06-print strings multiple times
We can use the multiplication operator to print the string multiple times. This is a very effective way to repeat strings.
N = int (input ("How many times you need to repeat:")) my_string = "Python\ n" print (my_string*n)
Output quantity
How many times you need to repeat:3 PythonPythonPython
Tip 07-concatenate two strings using the addition operator
You can concatenate various strings without using the join function. We can do this using only the addition operator (+).
A = "I Love" b = "Python" print (aqb)
Output quantity
I Love Python
Tip 08-multiple conditional operators
Two can combine two or more conditional operators in a program, and we can use logical operators. However, the same result can be obtained through the linking operator. For example, if we needed to print something when the value of the variable was greater than 10 and less than 20:00, the code would look like the following.
A = 15 if (a > 10 and a 20 then age = 25, print ("czz") else print ("unqualified")
Output quantity
Qualified
Tip 15-derive expressions using Python lists
List derivation expressions are a very compact way to create a list from another list. Look at the code below. The first is written using simple iterations, and the second is understood using lists.
Square_list = [] for x in range (1m 10): temp = Xerox 2 square_list.append (temp) print (square_list)
Output quantity
[1, 4, 9, 16, 25, 36, 49, 64, 81]
Derive expressions using lists
Square_list = [xylene 2 for x in range (1meme 10)] print (square_list)
Output quantity
[1, 4, 9, 16, 25, 36, 49, 64, 81]
Tip 16-convert a variable to an immutable item
The function frozenset () is used to convert a mutable iterable object into an immutable object. Using this method, we can freeze the value changes of the object.
My_list = [1 print 2 3 Jing 4 Jing 5] my_list = frozenset (my_list) my_list [3] = 7 print (my_list)
Output quantity
Traceback (most recent call last): File "", line 3, in TypeError: 'frozenset' object does not support item assignment
When we apply the frozenset () function to the list, the project allocation is limited.
Tip 17-rounding with floor and Ceil
Floor and Ceil are mathematical functions that can be used for floating-point numbers. The integer returned by the floor function is less than the floating-point number, while the integer returned by the ceil function is greater than the floating-point number. To use this feature, we must import the math module.
Import math my_number = 18.7print (math.floor (my_number)) print (math.ceil (my_number))
Output quantity
1819
Tip 18-return Boolean values
Sometimes we have to return a Boolean value by checking the conditions of some parameters. Instead of writing an if statement, we can return the condition directly. The following program will produce the same output.
Method I-use other conditions
Def function (n): if (n > 10): return True else: return False n = int (input ()) if (function (n): print ("Eligible") else: print ("Not Eligible")
Method II- has no other conditions
Def function (n): return n > 10 n = int (input ()) print ("Eligible") if function (n) else print ("Not Eligible")
Output quantity
Eligible
Tip 19-create a function one line
Lambda is an anonymous function in python that can be created on one line. The syntax for using the lambda function is given here.
Syntax: lambda parameter: expression
X = lambda a _ r _ c: a+b+c print (x _ (10 ~ m _ 20 ~ 30))
Output quantity
sixty
Tip 20-apply functionality to all elements in the list
Map is a high-order function that applies specific functionality to all elements in the list.
Syntax: map (function, iterable)
My_list = ["felix", "antony"] new_list = map (str.capitalize,my_list) print (list (new_list))
Output quantity
['Felix',' Antony']
Tip 21-use Lambda with map functionality
This function can be replaced with the lambda function in python. Create the following program to create the square of the list of numbers.
My_list = [1,2,3,4,5] new_list = map (lambda x: Xerox, my_list) print (list (new_list))
Output quantity
[1, 4, 9, 16, 25]
Tip 22-return multiple values from a function
The python function can return multiple values without any additional need. We can return values by separating them with commas.
Def function (n): return 1, 2, 2, 3, 3, 4, 3, 3, 4, 3, 3, 4, 3, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4,
Output quantity
1 2 3 4
Tip 23-filter values using the filter function
The filter function is used to filter some values in iterable objects. The syntax for the filter function is as follows.
Syntax: filter (function, iteration)
Def eligibility (age): return age > = 24 list_of_age = [10, 24, 27, 33, 30, 18, 17, 21, 26, 25] age = filter (eligibility, list_of_age) print (list (age))
Output quantity
[24, 27, 33, 30, 26, 25]
Tip 24-merge two dictionaries with Python
In python, we can merge two dictionaries without any specific method. The following code is an example of merging two dictionaries.
Dict_1 = {'One':1,' Two':2} dict_2 = {'Two':2,' Three':3} dictionary = {* * dict_1, * * dict_2} print (dictionary)
Output quantity
{'One': 1,' Two': 2, 'Three': 3}
Tip 25-get the size of the object
The memory size varies depending on the type of object. We can use the getsizeof () function in the sys module to get the memory of the object.
Import sys a = 5 print (sys.getsizeof (a))
Output quantity
twenty-eight
Tip 26-combine two lists into a dictionary
The zip code function has many advantages in python. Using the zip function, we can create dictionaries from two lists.
List_1 = ["One", "Two", "Three"] list_2 = [1Mae 2Mae 3] dictionary = dict (zip (list_1, list_2)) print (dictionary)
Output quantity
{'Two': 2,' One': 1, 'Three': 3}
Tip 27-calculate the execution time of the program
Time is another useful module in python that can be used to calculate execution time.
Import time start = time.clock () for x in range (1000): pass end = time.clock () total = end-start print (total)
Output quantity
0.00011900000000000105
Tip 28-remove duplicate elements from the list
An element that occurs multiple times is called a repeating element. We can simply delete duplicate elements using type conversions.
My_list = [1, set, 4, 1, 8, 2, 8, 5] my_list = list (set (my_list)) print (my_list)
Output quantity
[8, 1, 2, 4, 5]
Tip 29-print monthly calendars with python
The calendar module has many functions related to date-based operations. We can use the following code to print the monthly calendar.
Import calendar print (calendar.month ("2020", "06"))
Output quantity
June 2020 Mo Tu We Th Fr Sa Su 12 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
Tip 30-iterate with the zip feature
The zip function allows you to iterate through multiple iterating processes using loops. In the following code, both lists are iterated at the same time.
List_1 = ['an in zip in zip (list_1, list_2): print (x Magi y)]
Output quantity
A 1b 2c 3 Thank you for your reading, the above is the content of "what skills Python can write better code". After the study of this article, I believe you have a deeper understanding of what skills Python can write better code, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
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.