Please note: This article assumes that we all use Python 3
1. List-derived
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 the previous language experience will probably do
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]
Very concise, right? This is called a list derivation of Python.
2. Traversing the list
Continue, or the list above.
If possible try to avoid doing this:
Bag = [1, 2, 3, 4, 5] for I in range (len (bag)): print (Bag[i])
Instead, this should be the case:
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 have to do this, use the 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 straightforward.
3. Element Interchange
If you go from Java or C to Python, you might get used to this:
A = 5 B = 10# interchange A and btmp = a A = b b = tmp
But Python offers a more natural and better way!
A = 5 B = 10 # Interchange A and BA, B = B, a
Pretty enough, huh?
4. Initialize the list
If you want a list of 10 integers 0, you might first think:
Bag = [] for _ in range: bag.append (0)
Let's do it in a different way:
Bag = [0] * 10
Look, how graceful.
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 lists have changed, and we just 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 evils"
Ask yourself, is it necessary to initialize a list?
5. Constructing strings
You will often need to print the string. 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 (age) + "years ol D. I was born in "+ Born_in +". "Print (String)
Well, how messy does this look? You can use a beautiful and concise method instead,. format.
Do this:
Name = "Raymond" age = born_in = "Oakland, CA" string = "Hello My name was {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 easier. But there are common errors that come out when unpacking tuples:
def binary (): return 0, 1result = binary () zero = result[0] one = result[1]
This is not necessary, you can completely replace this:
def binary (): return 0, 1zero, one = Binary ()
If you need all the elements to be returned, use an underscore _:
Zero, _ = Binary ()
It's so efficient!
7. Access Dicts (dictionary)
You will also often write Key,pair (keys, values) to dicts.
If you try to access a nonexistent key to Dict, you may be inclined to do so in order 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] = 1for i in range: if I in Countr: print ("Count of {}: {}". Format (i, Countr[i]) Else: print ("Count of {}: {} ". Format (i, 0))
However, using get () is a better approach.
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:
print ("Count of {}: {}". Format (i, Countr.get (i, 0)))
Of course you can also use SetDefault to replace.
This also uses a simpler but more cost-consuming 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 ("C Ount of {}: {} ". Format (i, Countr.get (i, 0)))
You can also use the Dict derivation formula.
Countr = {num:bag.count (num) for num in bag}
These two methods are expensive because they traverse the list each time count is called.
8 Using libraries
The existing libraries just need to be imported and 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 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: print ("C Ount of {}: {} ". Format (i, countr[i]))
Some reasons to use the library:
1, the code is correct and tested.
2, their algorithms may be optimal, so that they can run faster.
3, abstraction: They point to clear and document-friendly, you can focus on those that have not yet been implemented.
4. Finally, it's already there, and you don't have to reinvent the wheel.
9. Slicing/stepping in the list
You can specify the start point and stop point, just like this list[start:stop:step].
We take out the first 5 elements of 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 then we remove the 5 elements from the list before stopping.
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)
Don't you see? 5 means to remove 5 elements from the end of the list.
If you want to manipulate the 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 this:
Bag = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] for Elem in bag[::2]: print (elem) # or with rangesbag = List (range (0,10,2)) print (bag)
This is the step in the list. List[::2] means that the traversal list takes two steps out of one element at a time.
You can use List[::-1] cool flip list.
Ten. Tab key or SPACEBAR
For a long time, mixing tabs and spaces will cause disaster and you'll see indentationerror:unexpected indent. Whether you choose the TAB key or the SPACEBAR, you should always keep it in your files and projects.
One reason to use a space instead of a tab is that the tab is not the same in all editors. Depending on the editor you are using, tab may be treated as 2 to 8 spaces.
You can also use spaces to define the tab when writing code. This way you can choose to use a few spaces to tab. Most Python users use 4 of spaces.
Summarize
The above is for everyone to summarize the development of Python to pay attention to the tips, I hope to learn from you and use Python can help, if there is doubt can message exchange.