Python White 10 common mistakes, you still do this operation?

Here are the ten Python useful tips and tricks. Some of them are beginners of the language often make mistakes.

Note: Suppose we are using the Python 3

1. List comprehensions

Do you have a list:bag = [1, 2, 3, 4, 5]

Now all the elements you want to double, it looks like this:[2, 4, 6, 8, 10]

Most beginners, based on prior experience of language would probably do it this way

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 Python's list comprehensions.

Click Trey Hunner's tutorial to see more of the description on the list comprehensions.

2. traverse the list

Continue, or the above list.

If possible, try to avoid doing so:

bag = [1, 2, 3, 4, 5]  
for i in range(len(bag)):  
    bag[i] = bag[i] * 2

Instead, it should be like this:

bag = [elem * 2 for elem in bag]

If x is a list, you can iterate over the elements of it. In most cases you do not need an index of each element, but if you do non, then use enumerate function. It looks like the following:

bag = [1, 2, 3, 4, 5]  
for i in range(len(bag)):  
    print(bag[i])

Very intuitive.

3. exchange element

If you are coming from java to Python or C language, you might be accustomed to this:

a = 5  
b = 10

# 交换 a 和 b
tmp = a  
a = b  
b = tmp

But Python provides a more natural way better!

a = 5  
b = 10  
# 交换a 和 b
a, b = b, a

Pretty enough, right?

4. Initialize list

If you want a list of integers 0 are 10, you may first think:

bag = []  
for _ in range(10):  
    bag.append(0)

It another way:

bag = [0] * 10

See more elegant.

Note: If you list contains a list, 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 have changed, and we just want to change the first list.

Modify it to read 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]]

Bearing in mind:

"Premature optimization is the root of all evil"
Ask yourself, initialize a list is necessary?

The construction string

You will often need to print a string. If there are a lot of 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)

Forehead, it looks much vexed it? You can use a pretty simple method instead, .format.

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(tuple)

Python allows you to return multiple elements in a function, it makes life easier. But when unpacking a tuple of qualifying this common errors:

def binary():  
    return 0, 1

result = binary()  
zero = result[0]  
one = result[1]

This is not necessary, you can replace this:

def binary():  
    return 0, 1

zero, one = binary()

If you need all the elements are returned, with the underscore _:

zero, _ = binary()

It is so efficient!

7. Access Dicts(dictionary)

You will often give dictswritten key,pair(key, value).

If you try to access a nonexistent dictin key, may be in order to avoid KeyErrormistakes, you tend to do 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, with get()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 use setdefaultinstead.

It also used a more simple, but a little extra cost 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(10):  
    print("Count of {}: {}".format(i, countr.get(i, 0)))

You can also use dictcomprehensions.

countr = {num: bag.count(num) for num in bag}

Both methods big overhead because they each countwill traverse the list is called.

8 Using libraries

Just import your existing library can do what you really want to do the.

Or that the previous example, we built a function to count the number of times a number that appears in the list. Well, there is already a library could 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:

Code is correct and tested.
Their algorithm might be optimal, so run faster.
Abstraction: they point to clear and document-friendly, you can focus on those that have not yet been implemented.
Finally, it is already there, and you do not have a recycling wheel.

9. In the list, the slice / step

You can specify starta point and the stoppoint, like this list[start:stop:step]. We removed before the 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 a slice, we specify the stoppoint is 5, then stop before it will remove the five elements from the list.

If the last five elements of how to do?

bag = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]  
for elem in bag[-5:]:  
    print(elem)

I do not understand it? -5It means out five elements from the end of the list.

If you want to list the elements interval operation, you might do:

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 this way:

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 list of steps. list[::2]Means through the list while a two-step extraction element.

You can use the list[::-1]cool flip lists.

10. tab key or the spacebar

Long term, the tab and spaces mix will result in a disaster, you'll see IndentationError: unexpected indent. Whether you choose the tab key or the spacebar, you should keep in your files and projects.

One reason to use spaces instead of a tab, tab is not the same in all editor. It depends on the use of the editor, tab might be considered as 2-8 spaces.

You can also define the tab with a space when writing code. So you can choose to use a few spaces as a tab. Most Python users with four spaces.

This is my learning Python skirt [784,758,214], whether you are big or small white cow, or would want to switch into the line can come together to learn to understand progress together! The inner skirt has development tools, a lot of dry goods and technical information to share! I hope the novice detours

Do not be too quick success, playing slowly, sophisticated.

If you feel interesting program, growth is no longer suffering, and have fun learning.

Guess you like

Origin blog.csdn.net/haoyongxin781/article/details/90347772