Whether it is python development or development in other languages, if we can master some useful tips and skills during development, it will certainly greatly improve our development efficiency, today I want to share with you some of the mistakes that are often made by beginners in python development. let's take a look. Note: in this article, we assume that we use Python 3.
1. list derivation
You have a list: bag = [1, 2, 3, 4, 5]
Now you want to double all elements and make them look like this: [2, 4, 6, 8, 10]
Most beginners will probably do this based on their previous language experience.
bag = [1, 2, 3, 4, 5] for i in range(len(bag)): bag[i] = bag[i] * 2
But there are better methods:
bag = [elem * 2 for elem in bag]
Very concise, right? This is called the list derivation of Python.
2. traverse the list
Continue, or the list above.
Avoid doing this if possible:
bag = [1, 2, 3, 4, 5] for i in range(len(bag)): print(bag[i])
Instead, it should be like this:
bag = [1, 2, 3, 4, 5] for i in bag: print(i)
If x is a list, you can iterate over its elements. In most cases, you do not need to index each element, but if you want to do so, use the enumerate function. It looks like below:
bag = [1, 2, 3, 4, 5] for index, element in enumerate(bag): print(index, element)
It is very intuitive and clear.
3. element swapping
If you switch from java or C to Python, you may get used to this:
A = 5 B = 10 # exchange a and btmp = a = B = tmp
But Python provides a more natural and better method!
A = 5 B = 10 # exchange a and ba, B = B,
Pretty?
4. initialization list
If you want a list of 10 integers 0, you may first think:
bag = [] for _ in range(10): bag.append(0)
In another way:
bag = [0] * 10
Look, more elegant.
Note: If your list contains a list, this will produce a small copy.
For example:
bag_of_bags = [[0]] * 5 # [[0], [0], [0], [0], [0]] bag_of_bags[0][0] = 1 # [[1], [1], [1], [1], [1]]
Oops! All lists are changed, and we just want to change the first list.
Change:
bag_of_bags = [[0] for _ in range(5)] # [[0], [0], [0], [0], [0]]bag_of_bags[0][0] = 1 # [[1], [0], [0], [0], [0]]
Remember:
"Premature optimization is the source of all evil"
Ask yourself, is it necessary to initialize a list?
5. construct a string
You often need to print strings. If there are many variables, avoid the following:
name = "Raymond" age = 22 born_in = "Oakland, CA" string = "Hello my name is " + name + "and I'm " + str(age) + " years old. I was born in " + born_in + "." print(string)
Well, how messy is this? You can use a beautiful and concise method instead of. format.
In this way:
name = "Raymond" age = 22 born_in = "Oakland, CA" string = "Hello my name is {0} and I'm {1} years old. I was born in {2}.".format(name, age, born_in) print(string)
Much better!
6. return tuples (tuples)
Python allows you to return multiple elements in a function, which makes life easier. However, the following common errors occur when the tuples are unwrapped:
def binary(): return 0, 1result = binary() zero = result[0] one = result[1]
This is unnecessary. you can replace it with this:
def binary(): return 0, 1zero, one = binary()
If you want all elements to be returned, use an underscore _:
zero, _ = binary()
This is so efficient!
7. access Dicts (dictionary)
You will also frequently write keys and pair (keys and values) to dicts ).
If you try to access a key that does not exist in dict, you may want to avoid KeyError:
countr = {} bag = [2, 3, 1, 2, 5, 6, 7, 9, 2, 7] for i in bag: if i in countr: countr[i] += 1 else: countr[i] = 1for i in range(10): if i in countr: print("Count of {}: {}".format(i, countr[i])) else: print("Count of {}: {}".format(i, 0))
However, using get () is a better method.
countr = {} bag = [2, 3, 1, 2, 5, 6, 7, 9, 2, 7] for i in bag: countr[i] = countr.get(i, 0) + 1for i in range(10): print("Count of {}: {}".format(i, countr.get(i, 0)))
You can also use setdefault instead.
This also uses a simpler but more costly method:
bag = [2, 3, 1, 2, 5, 6, 7, 9, 2, 7] countr = dict([(num, bag.count(num)) for num in bag])for i in range(10): print("Count of {}: {}".format(i, countr.get(i, 0)))
You can also use the dict derivation.
countr = {num: bag.count(num) for num in bag}
These two methods have a high overhead because they traverse the list every time count is called.
8. database used
You only need to import the existing database to do what you really want.
In the preceding example, we create a function to count the number of times a number appears in the list. So there is already a library to do this.
from collections import Counter bag = [2, 3, 1, 2, 5, 6, 7, 9, 2, 7] countr = Counter(bag)for i in range(10): print("Count of {}: {}".format(i, countr[i]))
Some database usage reasons:
1. the code is correct and tested.
2. their algorithms may be optimal, so they can run faster.
3. abstraction: they point to clarity and are document-friendly. you can focus on those that have not yet been implemented.
4. in the end, it's already there. you don't have to recreate the wheel.
9. Slice/step in the list
You can specify the start point and stop point, as shown in the following figure: list [start: stop: step].
Let's take out the first five elements in the list:
bag = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] for elem in bag[:5]: print(elem)
This is the slice. we specify that the stop point is 5, and 5 elements will be taken from the list before the stop.
What if the last five elements are used?
bag = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] for elem in bag[-5:]: print(elem)
Don't you understand? -5 indicates that five elements are extracted from the end of the list.
If you want to operate the element interval in the list, you may do the following:
bag = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] for index, elem in enumerate(bag): if index % 2 == 0: print(elem)
But you should do this:
Bag = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] for elem in bag [: 2]: print (elem) # or use rangesbag = list (range (0, 10, 2) print (bag)
This is the step in the list. List [: 2] means to traverse the list and retrieve an element in two steps at the same time.
You can use list [:-1] to flip the list.
10. the tab key or space key
For a long time, mixing tabs and spaces will cause a disaster. you will see IndentationError: unexpected indent. Whether you select the tab or space key, you should keep using it in your files and projects.
The reason for using spaces instead of tabs is that tabs are not the same in all editors. For the editor used, the tab may be treated as two to eight spaces.
You can also use spaces to define tabs when writing code. In this way, you can use several spaces as tabs. Most Python users use four spaces.
Summary
The above are the tips you should pay attention to during Python development. I hope it will be helpful for you to learn and use python. if you have any questions, please leave a message.
For more articles about Python development, please pay attention to PHP!