In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains the "what skills to write a better Python code", the article explains the content 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 to write a better Python code" bar!
1. Iterate using enumerate () instead of range (len ())
If we need to traverse a list and need to track the index and the current item, most people will use the range (len ()) syntax. In this case, we want to traverse a list, check to see if the current item is negative, and in this case set the value in the list to 0. Although the range (len ()) syntax works, it is better to use the built-in enumeration function. This returns the current index and current item as a tuple. Therefore, we can directly check the values here, or we can access items with indexes.
Data = [1,2,-3,-4] # weak: for i in range (len (data)): if data [I] < 0: data [I] = 0 # better: data = [1, 2,-3,-4] for idx, num in enumerate (data): if num < 0: data [idx] = 0
two。 Use list comprehension instead of the original for loop
Suppose we want to create a list with a specific value, in this case a list of all squares between 0 and 9. The tedious approach is to create an empty list, then use a for loop to calculate it, and append it to the list:
Squares = [] for i in range (10): squares.append (iTuni)
An easier way is list comprehension. Here we only need one line to do the same thing:
# better: squares = [iTuni for i in range (10)]
List comprehension is very powerful, even including if statements. Note that the use of list comprehension is a little controversial. It should not be overused, especially if it harms the readability of the code. But personally, I think this grammar is clear and concise.
3. Sort complex iterations using the built-in Sort () method
If we need to sort some iterable objects, such as lists, tuples, or dictionaries, we don't need to implement our own sorting algorithm. We can simply use the built-in sorting function. This automatically sorts the numbers in ascending order and returns a new list. If we want the results to be sorted in descending order, we can use the parameter reverse=True. As I said, this applies to any object that can be iterated over, so we can also use tuples here. Note, however, that the result is a list!
Data = (3,5,1,10,9) sortedsorted_data = sorted (data, reverse=True) # [10,9,5,3,1]
Now suppose we have a complex iterator. Here is a list, in which there is a dictionary, and we want to sort the list according to the age in the dictionary. To do this, we can also use the sort function, and then pass in the key parameters that should be used for sorting. The key must be a function, so here we can use lambda and an one-line function that returns the age.
Data = [{"name": "Max", "age": 6}, {"name": "Lisa", "age": 20}, {"name": "Ben", "age": 9}] sortedsorted_data = sorted (data, key=lambda x: X ["age"])
4. Use collections to store unique values
If we have a list with multiple values and only need unique values, a good trick is to convert our list to a collection. The collection is an unordered collection data type with no duplicate elements, so in this case, it removes all duplicate elements.
My_list = [1 set 2 3 removes duplicates 4 5 6 7 7] my_set = set (my_list) # removes duplicates
If we already know that we need a unique element, such as the prime number here, we can immediately create a collection with curly braces. This allows Python to do some internal optimizations, and it also has some convenient ways to calculate the intersection and differences between the two sets.
5. Generator saves memory
In tip 2, I showed you list comprehension. But lists are not always the best choice. Suppose we have a very large list of 10000 items that we want to calculate the sum of all the items. Of course, we can use lists to do this, but we may encounter memory problems. This is a perfect example of how we can use a generator. Similar to list comprehension, we can use the generator to understand that it has the same syntax, but uses parentheses instead of square brackets. The generator lazily calculates our elements, that is. Which generates only one entry at a time and only when requested If we calculate the sum of this generator, we see that we get the same correct result.
# list comprehension my_list = [i for i in range (10000)] print (sum (my_list)) # 49995000 # generator comprehension my_gen = (i for i in range (10000)) print (sum (my_gen)) # 49995000
6. Define default values in the dictionary with .get () and .setdefault ()
Suppose we have a dictionary with different keys, such as the item and the price of the item. At some point in the code, we want to get a count of entries and assume that the key is also included in the dictionary. When we simply try to access the key, it crashes our code and raises a KeyError. So it's better to use the .get () method in the dictionary. This also returns the value of the key, but if the key is not available, it does not raise a key error. Instead, it returns the default value we specified, or None if we don't specify it.
My_dict = {'item':' football', 'price': 10.00} price = my_dict [' count'] # KeyError! # better: price = my_dict.get ('count', 0) # optional default value
7. Count hashable objects with collections.Counter
If we need to count the number of elements in the list, there is a very convenient tool in the collections module that can do this. We just need to import counters from the collection and create counter objects with lists as parameters. If we print this, then for each item in the list, we can see the number of times this item appears, and it is sorted, with the most commonly used items first. It would be much better to calculate alone. If we want to get a count of an item, simply visit the item and it will return the corresponding count. If the item is not included, 0 is returned.
From collections import Counter my_list = [10, 10, 10, 5, 5, 2, 9, 9, 9, 9, 9, 9, 9] counter = Counter (my_list) print (counter) # Counter ({9: 6,10: 3,5: 2,2: 1}) print (counter [10]) # 3
8. Format the string with f-strings (Python 3.6 +)
This is a new feature since Python 3.6.It seems to me to be the best way to format strings. We just need to write an f in front of the string, and then we can use curly braces to access the variable in the string. This is simpler, simpler, and faster than the old formatting rules. In addition, we can write expressions that are evaluated at run time in curly braces. For example, if we want to output the square of the variable I, we can simply write this operation in the f string.
Name = "Alex" my_string = f "Hello {name}" print (my_string) # Hello Alex i = 10 print (f "{I} squared is {isimi}") # 10 squared is 100
9. Concatenate strings with .join ()
Suppose we have a list of different strings, and we want to combine all the elements into one string, with each word separated by a space. The bad way is to do this:
List_of_strings = ["Hello", "my", "friend"] # BAD: my_string = "" for i in list_of_strings: my_string + = I + ""
We define an empty string, then iterate through the list, and then append words and spaces to the string. You should know that strings are immutable elements, so here we have to create new strings every time. For large lists, this code can be very slow, so you should forget this method immediately! Better, faster, and more concise are the .join () methods:
.join () method: # GOOD: list_of_strings = ["Hello", "my", "friend"] my_string = "" .join (list_of_strings)
10. Merge dictionaries with double asterisk syntax (Python 3.5 +)
This syntax is a new syntax since Python 3.5. If we have two dictionaries and want to merge them, we can use curly braces and double asterisks for both dictionaries. Here Dictionary 1 has name and age, Dictionary 2 also has name and city. After merging with this concise syntax, we end up with all three keys in the dictionary.
D1 = {'name':' Alex', 'age': 25} D2 = {' name': 'Alex',' city': 'New York'} merged_dict = {* * D1, * * D2} print (merged_dict) # {' name': 'Alex',' age': 25, 'city':' New York'}
11. Simplify if statements with if x in list instead of checking each item individually
Suppose we have a list of dominant colors red, green, and blue. Somewhere in the code, we have a new variable that contains some colors, here c = red. Then we need to check whether the color comes from our dominant color. Of course we can check every item in the list like this:
Colors = ["red", "green", "blue"] c = "red" # cumbersome and error-prone if c = = "red" or c = = "green" or c = = "blue": print ("is main color")
But this can become very troublesome and we can easily make mistakes, for example, if we have a wrong red here. A simpler and better way is to use the syntax if x in list.
Thank you for your reading, the above is "what skills to write a better Python code" content, after the study of this article, I believe you have a deeper understanding of what skills to write a better Python code, the specific use of the need for you to practice and verify. 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.