Whether it is python development or the development of any other language, if we can master some useful tips and techniques during development, it will definitely greatly improve our development efficiency. Today, the editor and everyone What I’m sharing is some common mistakes that beginners often make when learning the language in Python development. Let’s take a look.
">
Please note: This article assumes that we are all using Python 3
1. List comprehension
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]
It’s very simple, right? ? This is called Python's list comprehension.
2. Traverse the list
Continue, or 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, then Just use the enumerate
function. It looks like the following: bag = [1, 2, 3, 4, 5]
for index, element in enumerate(bag):
print(index, element)
If you are from java. Or
C languageIf you switch 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
4. Initialization list
If you want a list of 10
integers0, you may first think of:
bag = [] for _ in range(10): bag.append(0)
Let’s try another way: bag = [0] * 10
Note: If your list contains a list, doing this will produce a shallow copy:
bag_of_bags = [[0]] * 5 # [[0], [0], [0], [0], [0]] bag_of_bags[0][0] = 1 # [[1], [1], [1], [1], [1]]
Oops! All lists have changed, and we just want to change the first one:
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 it necessary to initialize a list?5. ConstructString
You will often need to Print strings. If there are manyvariables
, 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 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)
Common mistakes
when unpacking tuples:def binary(): return 0, 1 result = binary() zero = result[0] one = result[1]
def binary(): return 0, 1 zero, one = binary()
zero, _ = binary()
7. Access Dicts (dictionaries)
You will also often writekey
, pair (key, value) to dicts. If you try to access a key that does not exist in the dict, you may be tempted to do this to avoid KeyError errors: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))
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)))
This is 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)))
countr = {num: bag.count(num) for num in bag}
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]))
bag = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] for elem in bag[:5]: print(elem)
bag = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] for elem in bag[-5:]: print(elem)
bag = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] for index, elem in enumerate(bag): if index % 2 == 0: print(elem)
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)
In the long run, mixing tabs and spaces will 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 the same 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.
Summary
The above are the tips that you should pay attention to in Python development. I hope it will be helpful to everyone in learning and using python. If you have any questions, you can leave a message to communicate.
The above is the detailed content of Share ten things to note when developing Python. For more information, please follow other related articles on the PHP Chinese website!