Below are ten useful tips and tricks in Python. Some of these are common mistakes that beginners make when learning the language.
Note: Assume we are all using Python 3
You have a list: bag = [1, 2, 3, 4, 5]
Now you want to double all the elements so that it looks like this: [2, 4, 6, 8, 10]
Most beginners will probably do it like 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 is a better way:
bag = [elem * 2 for elem in bag]
Very simple, right? This is called a Python list comprehension.
Click Trey Hunner’s tutorial to see more introduction to list comprehensions.
Continue with 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 don't need the index of each element, but if you must, use the enumerate function. It looks like below:
bag = [1, 2, 3, 4, 5] for index, element in enumerate(bag): print(index, element)
Very intuitive and clear.
If you are switching from Java or C language to Python, you may be used to this:
a = 5 b = 10 # 交换 a 和 b tmp = a a = b b = tmp
But Python provides a more natural and better method!
a = 5 b = 10 # 交换a 和 b a, b = b, a
Pretty enough, right?
If you want a list of 10 integers 0, you may first think of:
bag = [] for _ in range(10): bag.append(0)
Let’s try another way:
bag = [0] * 10
Look, how elegant.
Note: If your list contains lists, doing this will produce a shallow 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 only want to change the first list.
Change it:
bag_of_bags = [[0] for _ in range(5)] # [[0], [0], [0], [0], [0]] bag_of_bags[0][0] = 1 # [[1], [0], [0], [0], [0]]
Also remember:
"Premature optimization is the root of all evil"
Ask yourself, is initializing a list necessary?
You will 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)
Um, how messy does this look? You can use a nice and concise method instead, .format.
Do this:
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!
Python allows you to return multiple elements in a function, which makes life easier. However, common errors like this occur when unpacking tuples:
def binary(): return 0, 1 result = binary() zero = result[0] one = result[1]
This is not necessary, you can change it to this:
def binary(): return 0, 1 zero, one = binary()
If you need all elements to be returned, use an underscore_:
zero, _ = binary()
It’s so efficient!
You will also often write keys and pairs (keys, values) into dicts.
If you try to access a key that does not exist in the dict, you may want to avoid KeyError errors by doing this:
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] = 1 for 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 way.
countr = {} bag = [2, 3, 1, 2, 5, 6, 7, 9, 2, 7] for i in bag: countr[i] = countr.get(i, 0) + 1 for i in range(10): print("Count of {}: {}".format(i, countr.get(i, 0)))
Of course you can also use setdefault instead.
This also uses a simpler but more expensive 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 dict derivation.
countr = {num: bag.count(num) for num in bag}
These two methods are expensive because they traverse the list every time count is called.
Just import existing libraries and you can do what you really want.
Still talking about the previous example, let's build a function to count the number of times a number appears in a list. Well, there is already a library that can do such a thing.
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 reasons for using the library:
The code is correct and tested.
Their algorithm may be optimal and run faster.
Abstractions: They are clear and well-documented, and you can focus on what has not yet been implemented.
Finally, it's all there, you don't have to reinvent the wheel.
You can specify the start point and stop point, like this list[start:stop:step]. We take out the first 5 elements in the list:
bag = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] for elem in bag[:5]: print(elem)
This is slicing. We specify the stop point to be 5, and 5 elements will be taken out from the list before stopping.
What to do with the last 5 elements?
bag = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] for elem in bag[-5:]: print(elem)
Don’t you understand? -5 means take 5 elements from the end of the list.
If you want to operate on the intervals between elements in the list, you might do this:
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 it like this:
bag = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] for elem in bag[::2]: print(elem) # 或者用 ranges bag = list(range(0,10,2)) print(bag)
This is the step in the list. list[::2] means traversing the list and taking out an element in two steps.
You can use list[::-1] to do a cool flipping list.
In the long run, mixing tabs and spaces can cause disaster, and you will see IndentationError: unexpected indent. Whether you choose the tab key or the space bar, you should keep using it throughout your files and projects.
One reason to use spaces instead of tabs is that tabs are not created equal in all editors. Depending on the editor used, tabs may be treated as 2 to 8 spaces.
You can also use spaces to define tabs when writing code. This way you can choose how many spaces to use as tabs. Most Python users use 4 spaces.
English original text: The Python Way: 10 Tips
The above is the detailed content of 10 Tips for Python Development. For more information, please follow other related articles on the PHP Chinese website!