Please note: This article assumes that we are all using Python 3
1. List derivation type
You have a list:bag = [1, 2, 3, 4, 5]
Now you want to double all the elements to make it look like this: [2, 4, 6, 8, 10]
Most beginners, according to previous language experience will probably do this
Bag = [1, 2, 3, 4, 5] for
i in range (len (bag)):
bag[i] = bag[i] * 2
But there's a better way:
Bag = [Elem * 2 for Elem in bag]
It's neat, isn't it? This is called a list derivation of Python.
2. Traverse List
Continue, or the list above.
If possible avoid this:
Bag = [1, 2, 3, 4, 5] for
i in range (len (bag)):
print (Bag[i])
Instead, it should be:
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 the elements, but if you have to do this, use a enumerate
function. It looks like the bottom:
Bag = [1, 2, 3, 4, 5]
for index, element in enumerate (bag):
print (index, Element)
Very intuitive and clear.
3. Element Interchange
If you go from Java or C to Python, you might get used to it:
A = 5
B =
exchange A and b
tmp = a
a = b
b = tmp
But Python offers a more natural and better way!
A = 5
B = Ten
exchange A and B
A, B = B, a
Beautiful, isn't it?
4. Initializing the list
If you want a list of 10 integers 0, you might first think:
Bag = [] for
_ in range (a):
bag.append (0)
Put it another way:
Look, how elegant.
Note: If your list contains a list, doing so will produce a shallow copy.
As an example:
Bag_of_bags = [[0]] * 5 # [[0], [0], [0], [0], [0]]
bag_of_bags[0][0] = 1 # [[1], [1], [1], [1], [1]]
oops! All the listings are changed, and we just want to change the first list.
Change a 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]]
Also remember:
"Premature optimization is the root of all evils."
Ask yourself, is it necessary to initialize a list?
5. Construct string
You will often need to print strings. If there are many variables, avoid the following:
Name = "Raymond" Age
=
born_in = "Oakland, CA"
string = "Hello My name is" + name + "and I ' m" + STR (AG E) + "years old." I was born in "+ Born_in +". "
Print (String)
Well, how messy does it look? You can replace it with a nice, concise way .format
.
Do this:
Name = "Raymond" Age
=
born_in = "Oakland, CA"
string = "Hello I 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 to tuples (tuple)
Python allows you to return multiple elements in a function, which makes life simpler. But there are common errors that come out of qualifying when you unpack the tuples:
def binary (): return
0, 1 result
= binary ()
zero = result[0] one
= result[1]
This is not necessary, you can completely replace this:
def binary (): return
0, 1
zero, one = binary ()
If you need all the elements to be returned, use an underscore _:
It's so efficient!
7. Visit Dicts (dictionary)
You will also often write to Dicts key
, pair
(keys, values).
If you try to access a non-existent one dict
key
, you may be tempted to do so in order to avoid the KeyError
error:
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:
if I in Countr:
print ("Count of {}: {}". Format (i, Countr[i]))
Else :
print ("Count of {}: {}". Format (i, 0))
But it get()
's a better way to do it.
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:
print ("Count of {}: {}". Format (i, Countr.get (i, 0))
Of course you can use it setdefault
instead.
It also uses a simpler but more costly approach:
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:
print ("Count of {}: {}". Format (i, Countr.get (i, 0))
You can also use the dict
deduced formula.
Countr = {num:bag.count (num) for num in bag}
Both of these methods are expensive because they traverse the list every time they count
are invoked.
8 Using libraries
Existing libraries just import you can do what you really want to do.
Or the previous example, we built a function to count the number of occurrences of a number in the list. Well, there's 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 (1 0):
print ("Count of {}: {}". Format (i, Countr[i])
Some reasons to use the library:
1, the code is correct and tested.
2, their algorithm may be optimal, so that the faster run.
3, Abstract: They point to clear and 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 reinvent the wheel.
9. Slicing/stepping in the list
You can specify start
the points and stop
points, just 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 the slice, we specify the stop
point is 5, before stopping will be removed from the list of 5 elements.
What if the last 5 elements were to be done?
Bag = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] for
Elem in bag[-5:]:
print (Elem)
Didn't see it, understood? -5 means to remove 5 elements from the end of the list.
If you want to operate on the element interval 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 this:
Bag = [0, 2, 3, 4, 5, 6, 7, 8, 9] for
Elem in bag[::2]:
print (Elem)
# or with ranges bag
= List (0,10, 2)
print (bag)
This is the stepping in the list. list[::2]
it means to iterate through the list and take out an element two steps at a time.
You can use list[::-1]
a cool flip list.
The TAB key or the SPACEBAR
For a long time, the combination of tab and space can cause disaster, as you will see IndentationError: unexpected indent
. Whether you choose the TAB key or the SPACEBAR, you should keep it in your files and projects.
One reason to use a space instead of the TAB key is that the tab is not the same in all editors. Depending on the editor used, tab may be treated as 2 to 8 spaces.
You can also use spaces to define tab in writing code. This way you can choose to use a few spaces as tab. Most Python users use 4 spaces.
Summarize
The above is for you to summarize the Python development to note the tips, I hope to learn and use Python can help, if you have questions can be exchanged message.