In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article focuses on "what are the tips for accelerating Python programming". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let the editor take you to learn "what are the tips for speeding up Python programming"?
1. Negative index
People like to use sequences because when we know the order of elements, we can manipulate them in order. Strings, tuples, and lists are the most common sequence data types in Python. We can use the index to access individual items. Like other major programming languages, Python supports 0-based indexes, in which we use zeros to access the first element in square brackets. In addition, we can use slice objects to retrieve specific elements of the sequence, as shown in the following code example.
> > # Positive Indexing... Numbers = [1,2,3,4,5,6,7,8]. Print ("First Number:", numbers [0]). Print ("First Four Numbers:", numbers [: 4]). Print ("Odd Numbers:", numbers [:: 2]). First Number: 1 First Four Numbers: [1, 2, 3, 4] Odd Numbers: [1, 3, 5, 7]
However, Python goes a step further by supporting negative indexes. Specifically, we can use-1 to refer to the last element in the sequence and count backwards. For example, the index of the last element is-2, and so on. Importantly, negative indexes can also be used with positive indexes in sliced objects.
> > # Negative Indexing... Data_shape = (100,50,4). Names = ["John", "Aaron", "Mike", "Danny"]. Hello = "Hello World!". Print (data_shape [- 1])... Print (names [- 3 muri 1]). Print (Helo [1:-1:2])... 4 ['Aaron',' Mike'] el ol
two。 Check whether the container is empty
Containers are those container data types that can store other data. Some of the frequently used built-in containers are tuples, lists, dictionaries, and collections. When dealing with these containers, we often need to check to see if they contain any elements before performing other operations. Indeed, we can check the length of these containers, which corresponds to the number of items that have been stored. When the length is 00:00, the container is empty. A simple example is shown below.
If len (some_list) > 0: # do something here when the list is not empty else: # do something else when the list is empty
However, this is not the best way to Pythonic. Instead, we can simply examine the container itself, which will be evaluated when the container True contains elements. Although the following code shows you the main container data types, this usage can also be applied to strings (that is, any non-empty string is True).
Def check_container_empty (container):... If container:... Print (f "{container} has elements."). Else:... Print (f "{container} doesn't have elements."). Check_container_empty ([1,2,3]). Check_container_empty (set ())... Check_container_empty ({"zero": 0, "one": 1}). Check_container_empty (tuple ())... [1,2,3] has elements. Set () doesn't have elements. {'zero': 0,' one': 1} has elements. () doesn't have elements.
3. Use Split () to create a list of strings
We often use strings as identifiers for specific objects. For example, we can use a string as a key in a dictionary. In data science projects, a string is usually the column name of the data. When selecting multiple columns, it is inevitable that you need to create a list of strings. Indeed, we can create strings using the text in the list. However, we have to write pairs of quotation marks to enclose each string, which is a bit cumbersome for "lazy" people. Therefore, I prefer to use the split () method of a string to create a list of strings, as shown in the following code snippet.
# List of strings... # The typical way... Columns = ['name',' age', 'gender',' address', 'account_type']. Print ("* Literals:", columns)... # Do this instead... Columns = 'name age gender address account_type'.split ()... Print ("* Split with spaces:", columns)... # If the strings contain spaces, you can use commas instead... Columns = 'name, age, gender, address, account type'.split (',')... Print ("* Split with commas:", columns)... * Literals: ['name',' age', 'gender',' address', 'account_type'] * Split with spaces: [' name', 'age',' gender', 'address',' account_type'] * Split with commas: ['name',' age', 'gender',' address', 'account type']
As shown above, split () by default, this method uses spaces as delimiters and creates a list of strings based on strings. It is worth noting that when you create a list of strings that contain certain elements that contain spaces, you can choose to use other types of delimiters (for example, commas).
This usage is inspired by some built-in features. For example, when you create a tuple class, we can do this: Student = namedtuple ("Student", ["name", "gender", "age"]). The string list specifies the attributes of the tuple. However, you can also define the class to support it locally by defining Student = namedtuple ("Student", "name gender age"). For another instance, create an Enum class that supports the same alternative solution.
4. Ternary expression
In many use cases, we need to define variables with specific values based on conditions, and we can simply use if. Else statement to check the condition. However, it takes several lines of code. If you deal with the assignment of only one variable, you may need to use a ternary expression that checks the condition and completes the assignment in just one line of code. In addition, its format is shorter, making the code more concise. Consider the following example.
# The typical way if score > 90: reward = "1000 dollars" else: reward = "1000 dollars" # Do this instead reward = "1000 dollars" if score > 90 else "500 dollars"
Sometimes we can get some data from a defined function, and we can take advantage of this and write a simple operation of a ternary expression, as shown below.
# Another possible scenario # You got a reward amount from somewhere else, but don't know if None/0 or not reward = reward_known or "500dollars" # The above line of code is equivalent to below reward = reward_known if reward_known else "500dollars"
5. Statements with file objects
We often need to read data from the file and write the data to the file. The most common way is to simply open a file using the built-in open () function, which creates a file object that we can manipulate.
> # Create a text file that has the text: Hello World!... # Open the file and append some new data. Text_file0 = open ("hello_world.txt", "a"). Text_file0.write ("Hello Python!")... # Open the file again for something else... Text_file1 = open ("hello_world.txt"). Print (text_file1.read ())... Hello World!
In the previous code snippet, we started with a text file with the text "Hello World!". Then we append some new data to the file. However, after a while, we want to process the file again. When we read the text file, it still has old data. In other words, the additional text is not included in the text file.
This is because we did not close the file object at first. If you do not close the file, you cannot save the changes. Indeed, we can close () explicitly call this method on the file object. However, we can do this using the "with" statement, which automatically closes the file object for us, as shown below. After we have finished working on the file, we can verify that the file is closed by accessing the closed property of the file object.
With open ("hello_world.txt", "a") as file:... File.write ("Hello Python!"). With open ("hello_world.txt") as file:... Print (file.read ()). Print ("Is file close?", file.closed). Hello World!Hello Python!Hello Python! Is file close? True
In more general terms, the with statement is the syntax for using the context manager in Python. The previous example involves file manipulation because these files are shared resources and we are responsible for releasing them. The context manager can help us get the job done. As shown earlier, when the file operation is finished, the file is automatically closed using the with statement.
6. Evaluate multiple conditions
Usually, we need to evaluate multiple conditions. There are several possible options. For numeric values, we can compare the same variable multiple times. In this case, we can link to these comparisons.
# Multiple Comparisons # The typical way if a
< 4 and a >1: # do something here# Do this instead if 1
< a < 4: # do somerthing here 在其他一些情况下,我们可以进行多个相等比较,并且可以使用以下in关键字进行成员测试。 # The typical way if b == "Mon" or b == "Wed" or b == "Fri" or b == "Sun": # do something here# Do this instead, you can also specify a tuple ("Mon", "Wed", "Fri", "Sun") if b in "Mon Wed Fri Sun".split(): # do something here 另一种技术是使用内置的all()和any()函数用于评估多个条件的功能。具体而言,该all()函数将评估何时迭代中的元素全部为True,因此该函数适合于替换一系列AND逻辑比较。另一方面,该any()函数的计算结果为True当迭代中的任何元素为True,因此适合替换一系列OR逻辑运算。相关示例如下所示。 # The typical ways if a < 10 and b >5 and c = = 4: # do somethingif a
< 10 or b >5 or c = 4: # do something# Do these instead if all ([a
< 10, b >5, c = = 4]): # do somethingif any ([a
< 10, b >5, c = = 4]): # do something
7. Use default values in function declarations
In almost all Python projects, most of the code involves creating and calling functions. In other words, we are constantly dealing with function declarations and refactoring. In many cases, we need to call a function multiple times. This feature will vary slightly depending on the parameter set. However, sometimes one set of parameters may be more commonly used than the other, in which case we should consider setting the default value when declaring the function. Consider the following simple example.
# The original form: def generate_plot (data, image_name): "This function creates a scatter plot for the data"# create the plot based on the data... If image_name: # save the image... # In many cases, we don't need to save the image generate_plot (data, None) # The one with a default value def generate_plot (data, image_name=None): pass# Now, we can omit the second parameter generate_plot (data)
One thing to note is that if you want to deal with variable data types (such as lists, collections) when setting default values, be sure to use None instead of constructors (for example, arg_name = []). Because Python creates the function object at the defined location, the blank list provided will be "stuck" by the function object. In other words, the function object is not created immediately when it is called. Instead, we will process the same function object in memory, including the default mutable object it originally created, which can lead to unexpected behavior.
8. Use counters for element counting
When we have multiple items in a list, tuple, or string (for example, multiple characters), we often want to calculate how many elements there are in each item. To do this, you can write some tedious code for this feature.
Words = ['an',' boy',' girl', 'an',' boy',' dog', 'cat',' Dog', 'CAT',' an','GIRL', 'AN',' dog', 'cat',' cat', 'bag',' BAG', 'BOY',' boy', 'an']. Unique_words = {x.lower () for x in set (words)}. For word in unique_words:... Print (f "* Count of {word}: {words.count (word)}")... * Count of cat: 3 * Count of bag: 1 * Count of boy: 3 * Count of dog: 2 * Count of an: 5 * Count of girl: 1
As shown above, we must first create a collection that contains only unique words. Then we iterate over the word set and use the count () method to find out the occurrence of each word. However, there is a better way to use the Counter class to accomplish this counting task.
From collections import Counter. Word_counter = Counter (x.lower () for x in words)... Print ("Word Counts:", word_counter)... Word Counts: Counter ({'an': 5,' boy': 4, 'cat': 4,' dog': 3, 'girl': 2,' bag': 2})
This counter class is available in the collections module. To use this class, we just need to create a generator:,x.lower () for x in words where each item will be counted. As we can see, the Counter object is a dict-like mapping object, where each key corresponds to a unique item in the word list, and the value is the count of those items.
In addition, if we are interested in finding the items that appear most frequently in the word list, we can use the most_common () method of the Counter object. The following code shows this usage. We only need to specify an integer (N) to find the N items that are most frequent in the list. Incidentally, this object will also be used with other sequence data, such as strings and tuples.
> > # Find out the most common item... Print ("Most Frequent:", word_counter.most_common (1)) Most Frequent: [('an', 5)] > > # Find out the most common 2 items. Print ("Most Frequent:", word_counter.most_common (2)) Most Frequent: [('an', 5), (' boy', 4)]
9. Sort by different order requirements
Sorting items in a list is a common task in many projects. The most basic sort is based on numeric or alphabetical order, and we can use the built-in sorted () function. By default, the sorted () function sorts the list in ascending order (in fact, it can be iterated). If you specify the reverse parameter as True, you can get the items in descending order. Some simple uses are as follows.
> > # A list of numbers and strings... Numbers = [1,3,7,2,5,4]. Words = ['yay',' bill', 'zen',' del']... # Sort them... Print (sorted (numbers))... Print (sorted (words))... [1,2,3,4,5,7] ['bill',' del', 'yay',' zen'] > # Sort them in descending order. Print (sorted (numbers, reverse=True)). Print (sorted (words, reverse=True))... [7, 5, 4, 3, 2, 1] ['zen',' yay', 'del',' bill']
In addition to these basic uses, we can also specify the key parameter so that complex items can be sorted, such as tuple lists. Consider the following example of this situation.
> > # Create a list of tuples... Grades = [('John', 95), (' Aaron', 99), ('Zack', 97), (' Don', 92), ('Jennifer', 100), (' Abby', 94), ('Zoe', 99), (' Dee', 93)] > > # Sort by the grades, descending. Sorted (grades, key=lambda x: X [1], reverse=True) [('Jennifer', 100), (' Aaron', 99), ('Zoe', 99), (' Zack', 97), ('John', 95), (' Abby', 94), ('Dee', 93), (' Don', 92)] > > # Sort by the name's initial letter, ascending. Sorted (grades, key=lambda x: X [0] [0]) [('Aaron', 99), (' Abby', 94), ('Don', 92), (' Dee', 93), ('John', 95), (' Jennifer', 100), ('Zack', 97), (' Zoe', 99)]
The above code shows us two examples of advanced sorting by using the lambda function passed to the key parameter. The first uses descending order to sort items, and the second uses the default ascending order to sort items. We want to combine these two requirements, and if we consider using this reverse parameter, we may get an incorrect sort tree, because if you try to sort by multiple criteria, the reverse parameter will apply to all parameters. See the code snippet below.
> > # Requirement: sort by name initial ascending, and by grades, descending... # Both won't work... Sorted (grades, key=lambda x: (x [0] [0], x [1]), reverse=True) [('Zoe', 99), (' Zack', 97), ('Jennifer', 100), (' John', 95), ('Dee', 93), (' Don', 92), ('Aaron', 99), (' Abby', 94)] > > sorted (grades, key=lambda x: (x [0] [0], x [1]), reverse=False) [('Abby']) 94), ('Aaron', 99), (' Don', 92), ('Dee', 93), (' John', 95), ('Jennifer', 100), (' Zack', 97), ('Zoe', 99)] > # This will do the trick. Sorted (grades, key=lambda x: (x [0] [0],-x [1])) [('Aaron', 99), (' Abby', 94), ('Dee', 93), (' Jennifer', 92), ('Jennifer', 95), (' Zoe', 99), ('Zack', 97)]
As you can see, it has no effect by setting the reverse parameter to True or False. Instead, the trick is to reverse the scores, so when you sort in the default ascending order, the scores are sorted in reverse because of the inversion of these values. However, this method has a warning because reversals can only be used for numeric values, not strings.
10. Don't forget defaultdict
Dictionary is a valid data type, which enables us to store data in the form of key-value pairs. It requires that all keys are hashable, and storing this data may involve the use of hash tables. This method allows data retrieval and insertion with O (1) efficiency. However, it should be noted that we have other dictionaries available in addition to the built-in dict type. Among them, I want to discuss the defaultdict type. Unlike the built-in dict type, defaultdict allows us to set the default factory function, which creates an element when the key does not exist.
Student = {'name': "John",' age': 18}. Student ['gender']... Traceback (most recent call last): File "", line 2, in KeyError: 'gender'
Suppose we are working on words and want to group the same characters as lists, and these lists are associated with characters as keys. This is a naive implementation using the built-in dict type. It is worth noting that it is important to check whether the dict object has a letter key, because calling the append () method throws a KeyError exception if the key does not exist.
Letters = ["a", "a", "c", "d", "d", "c", "a", "b"]. Final_dict = {}... For letter in letters:... If letter not in final_dict:... Final_ letter = []... Final_ letter .append (letter). Print ("Final Dict:", final_dict)... Final Dict: {'aqu: [' asituation,'a'], 'croup: [' croup,'c'], 'dice: [' dice,'d'], 'baked: [' b']}
Let's take a look at how to write more concise code using defaultdict. Although the example is simple, it just gives us some ideas about the defaultdict class, which eliminates the need to deal with keys that do not exist in the dictionary object.
From collections import defaultdict. Final_defaultdict = defaultdict (list)... For letter in letters:... Final_ default letters [letter] .append (letter). Print ("Final Default Dict:", final_defaultdict)... Final Default Dict: defaultdict (, {'averse: [' asides, 'aways,' a'], 'caches: [' clocked,'c'], 'dudes: [' dudes,'d'], 'baked: [' b']}) so far, I believe you have a better understanding of "what are the tips for speeding up Python programming". You might as well do it in practice! Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
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.