The paper contains 4433 words and is expected to last 13 minutes
Photo source: Unsplash
There is a place for 1000 hamlets in 1000 readers and 1000 programmers to ask “what is the best language?” Java, Python, PHP, C++ all have their place. But if you ask the king of programming language popularity, it’s really Python.
According to Stack Overflow data, Python is the fastest growing programming language in usage.
According to a recent report by Forbes, Python usage has grown 456% in the last year. Netfix, IBM, and hundreds of other companies use Python. Dropbox is also created in Python. Dice’s research shows that Python is one of the hottest techniques in the world, as well as the most popular programming language in terms of popularity.
Why is Python so attractive?
That’s because Python has five advantages over other programming languages:
1. Compatible with mainstream platforms and operating systems.
2. Includes many open source frameworks and tools.
3. The code has readability and maintainability
4. A powerful standard library
5. Standard test-driven development
Python is becoming increasingly popular due to its low barriers to learning and wide prospects. Today, We continue to bring you 10 useful python code tips to help you complete your daily work
Photo source: Unsplash
10 Python tips
1. Use ZIP to process the list
Suppose you want to merge lists of the same length and print the result. There is also a more general way to get the desired result using the zip () function:
countries= [‘France’, ‘Germany’, ‘Canada’]
capitals = [‘Paris’, ‘Berlin’, ‘Ottawa’]
for country, capital in zip(countries,capitals):
print(country, capital) # FranceParis
GermanyBerlin
CanadaOttawa
Use Python collections
Python Collections are container data types: lists, collections, tuples, dictionaries. The Collections module provides high-performance data types that enhance your code, making things simpler and easier. It also provides a lot of functionality, as illustrated below using the Counter() function.
The Counter() function takes an iterable (such as a list or tuple) and returns a Counter dictionary. The dictionary key is the only element that exists in the iterator, and the value of each key is a count of the number of occurrences of that element in the iterator.
To create a Counter object, pass an iteration (list) to the Counter () function as follows.
fromcollections import Countercount = Counter([‘a’,’b’,’c’,’d’,’b’,’c’,’d’,’b’])
print(count) # Counter({‘b’: 3, ‘c’: 2, ‘d’: 2, ‘a’: 1})
3. Use the itertools
Python’s IterTools module is a collection of tools for handling iterators. Itertools contains a variety of tools for generating iterable results of input data. Take itertools.combinations() as an example. Itertools.binations () is used to build combinations. These are possible combinations of the inputs.
To illustrate this point, take a real life example:
Suppose there are four teams in a tournament, and each team has to play each other in a tournament. The task was to list all possible combinations of competing teams.
The code is as follows:
importitertools
friends = [‘Team 1’, ‘Team 2’, ‘Team 3’, ‘Team 4’]
list(itertools.combinations(friends, r=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’)]
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 only needs to contain one of them. Similarly, you can use itertools.permutations() and other functions from this module. For a more complete reference, consult this tutorial.
4. Return multiple values from a function
Python can return multiple values from function calls, a feature not available in many other popular programming languages. In this case, the return value should be a comma-separated list of values, which Python then constructs a tuple and returns to the caller. A 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 comprehensions
List comprehensions are used to create new lists from other iterables. When a list derivation returns a list, it consists of square brackets containing an expression that is executed for each element and for the for loop that loops through each element. List derivation is faster because the Python interpreter has been optimized to detect predictable patterns during loops.
As follows, square the first five integers using a list derivation:
m = [x** 2 for x in range(5)]
print(m) # [0, 1, 4, 9, 16]
Another example is to use list comprehensions to find common numbers in two lists
list_a =[1, 2, 3, 4]
list_b = [2, 3, 4, 5]
common_num = [a for a in list_a for b in list_b if a == b]
print(common_num) # [2, 3, 4]
6. Convert two lists into a dictionary
Photo source: Unsplash
Suppose you have two lists, one containing students’ names and the other containing students’ scores. 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 stitching
A for loop can be used 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 follows:
characters= [‘p’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’]
word = “”.join(characters)
print(word) # python
Use the sorted() function
Using the built-in sorted() function in Python, which makes sorting any sequence easy, does a lot of the hard work. Sorted () sorts any sequence (list, tuple) and returns a list of sorted elements. Order 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. Use enumerate() to iterate
The Enumerate () method adds a counter to the iterable and returns it as an enumeration object.
Here’s a classic coding interview question (often referred to as the Fizz Buzz question).
Write a program to print the numbers in a list. If the number is a multiple of 3, fizz is displayed. Is a multiple of 5 and outputs “buzz”; Both 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. Using Python generators
Generator functions allow the creation of iterator-like functions. They allow programmers to create iterators in a simple and quick way. Here is an example to illustrate this concept.
Suppose you want to sum the first 10,000,000 perfect squares starting at 1.
Looks easy, doesn’t it? This is easy to do using a list derivation, but it requires too much input. The following is an example:
t1 =time.clock()
sum([i * i for i in range(1, 100000000)])
t2 = time.clock()
time_diff = t2 – t1
Print (f”It took {time_diff} Secs to execute this method”) # Ittook 13.197494000000006 Secs to execute this method
This method is not flexible enough to increase the number of perfect squares of summation due to the large amount of computation time required. This is where the Python generator comes in. After replacing square brackets with parentheses, the list derivation changes 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”It took {time_diff} Secs to execute this method”) # Ittook 9.53867000000001
As above, the time taken has been greatly reduced. The larger the input, the more significant the reduction effect.
Summary:
Photo source: Unsplash
As AI heats up, Python will become increasingly important as the language of choice for ai development. The old saying “learn math, physics and chemistry well, you can go anywhere” may be changed now — “Learn Python well, you can go anywhere”.
So, what are you waiting for? Pick up these 10 useful Python hacks to make your day work even better
Leave a comment like follow
We share the dry goods of AI learning and development. Welcome to pay attention to the “core reading technology” of AI vertical we-media on the whole platform.
(Add wechat: DXSXBB, join readers’ circle and discuss the freshest artificial intelligence technology.)