In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-21 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly explains "10 Tips sharing of Python language". The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "10 Tips sharing of Python language".
10 Python Tips
1. Working with lists with ZIP
Suppose you want to merge lists of the same length and print the results. There is also a more general way to get the desired result with the zip () function, as follows:
Countries= ['France',' Germany', 'Canada'] capitals = [' Paris', 'Berlin',' Ottawa'] for country, capital in zip (countries,capitals): print (country, capital) # FranceParis GermanyBerlin CanadaOttawa
two。 Use python collections
Python collections is the container data type, namely, lists, collections, tuples, dictionaries. The Collections module provides high-performance data types that enhance the code, making the work simpler and easier. It also provides many features, which are demonstrated using the Counter () function below.
The Counter () function takes an iterable object, such as a list or tuple, and returns an Counter dictionary. The key of the dictionary is the only element that exists in the iterator, and the value of each key is a count of the number of times that element appears in the iterator.
To create a Counter object, pass an iterative (list) to the Counter () function as follows.
Fromcollections import Countercount = Counter (print (count) # Counter ({'baked: 3,' clockwise: 2, 'dumped: 2,' averse: 1}))
3. Use itertools
Python's itertools module is a collection of tools for working with iterators. Itertools includes a variety of tools for generating iteratable results of input data. Take itertools.combinations () as an example. Itertools.combinations () is used to build the composition. These are possible combinations of inputs.
Give a real-life example to illustrate the above point:
Suppose there are four teams in a tournament, and in the league stage, each team has to play against every other team. The task is to list the possible combinations of all the competing teams.
The code is as follows:
Importitertools friends = ['Team 1,' Team 2, 'Team 3,' Team 4'] list (itertools.combinations (friends, ritual 2)) # [('Team 1,' Team 2'), ('Team 1,' Team 3'), ('Team 1,' Team 4'), ('Team 2,' Team 3'), ('Team 2,' Team 4'), ('Team 3,' Team 4')]
It is important to note that the order of values is not important. Because ('Team 1,' Team 2') and ('Team 2,' Team 1') represent the same pair, the output list needs to include only one of them. Similarly, you can use itertools.permutations () and other functions from the module. For more complete references, please refer to this tutorial.
4. Returns multiple values from a function
Python can return multiple values from function calls, a feature that many other popular programming languages do not have. In this case, the return value should be a comma-separated list of values, and then python constructs a tuple and returns it to the caller. The code example is as follows:
Defmultiplication_division (num1, num2): return num1*num2, num1/num2product,division = multiplication_division (15,3) print ("Product=", product, "Quotient =", division) # Product= 45 Quotient = 5.0
5. Use list derivation
List derivation is used to create new lists from other iterable objects. When list deduction returns a list, it consists of square brackets that contain expressions that are executed for each element and for the for loop that iterates through each element. List derivation is faster because the python interpreter is optimized so that predictable patterns can be found during the loop.
As follows, use the list derivation to square the first five integers:
M = [xylene * 2 for x in range (5)] print (m) # [0,1,4,9,16]
For example, use list deduction to find common numbers in two lists
List_a = [1,2,3,4] list_b = [2,3,4,5] common_num = [a for an in list_a for b in list_b if a = = b] print (common_num) # [2,3,4]
6. Convert two lists into one dictionary
Suppose there are two lists, one with the student's name and the other with the student's score. Using the zip function, convert the two lists into a dictionary, as follows:
Students= ["Peter", "Julia", "Alex"] marks = [84,65,77] dictionary = dict (zip (students, marks)) print (dictionary) # {'Peter': 84,' Julia': 65, 'Alex': 77}
7. String concatenation
You can use for loops to add elements one by one when concatenating strings, but this is very inefficient (especially if the list is long). In python, strings are immutable, so when concatenating strings, you must copy the left and right strings into the new string.
A better approach is to use the join () function, as shown below:
Characters= ['packs,' yearly, 'tweets,' hacks, 'oaks,' n'] word = "" .join (characters) print (word) # python
8. Use the sorted () function
Using the built-in function sorted () in python, you can easily sort any sequence, and it can do a lot of hard work. Sorted () can sort any sequence (list, tuple) and return a list of sorted elements. Sort the numbers in ascending order as follows:
Sorted ([3, 5, 2, 1, 4]) # [1, 2, 3, 4, 5]
Sort the strings in descending order as follows:
Sorted (['france','germany',' canada', 'india',' china'], reverse=True) # ['india',' germany','france', 'china',' canada']
9. Iterate with enumerate ()
The Enumerate () method adds a counter to an iterable object and returns as an enumerated object.
The following is a classic coding interview question (often referred to as a Fizz Buzz question).
Write a program to print the numbers in the list. If the number is a multiple of 3, output "fizz"; if it is a multiple of 5, output "buzz"; if it is a multiple of 3 and 5, output "fizzbuzz".
Numbers= [30, 42, 28, 50, 15] for I, num in enumerate (numbers): if num% 3 = = 0 and num% 5 = = 0: numbers [I] = 'fizzbuzz' elif num% 3 = = 0: numbers [I] =' fizz' elif num% 5 = = 0: numbers [I] = 'buzz' print (numbers) # [' fizzbuzz', 'fizz', 28,' buzz', 'fizzbuzz']
10. Use python generators (generator)
The generator function allows you to create functions similar to iterators. They allow programmers to create iterators in a simple and fast way. Here is an example to illustrate this concept.
Suppose you want to sum the first 100000000 complete squares starting at 1.
It looks easy. You can easily do this with list derivation, but it takes too much input. Here is an example:
T1 = time.clock () sum ([I * i for i in range (1, 100000000)]) T2 = time.clock () time_diff = T2-T1 print (f "Ittook {time_diff} Secs to execute this method") # Ittook 13.1974940000006 Secs to execute this method
When increasing the complete square of the sum, this method is not flexible enough because it takes a lot of time to calculate. This is when the python generator comes in handy. After replacing square brackets with parentheses, the list deduction is changed to a generator expression. Now calculate the time spent:
T1 = time.clock () sum ((I * i for i in range (1, 100000000)) T2 = time.clock () time_diff = T2-T1 print (f "Ittook {time_diff} Secs to execute this method") # Ittook 9.53867000000001 Secs to execute this method
Thank you for reading, the above is the content of "10 Tips of Python language sharing". After the study of this article, I believe you have a deeper understanding of the problem of sharing 10 tips of Python language, 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.