These ten tips will help you write Python code is more elegant

Original link: https://mp.weixin.qq.com/s?src=11×tamp=1571983066&ver=1932&signature=EgN5K1yMn8*6OfV5pEzb7WwC7echhfDdpNssdqkdKL3Sdo9a*1fes*QJqJTsOuO1IOYWIQqgmNWRfqxS5XgNfnQJIuO0-Gu*ex7LnjCiNcdBX4YL0sczQ0rcQsuUdKGq&new=1

From: Code rural network, Translator: Wang Jian

Link: http: //www.codeceo.com/article/python-10-tips.html

Original: http: //raymondtaught.me/the-python-way-10-tips/

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

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

'''
更多Python学习资料以及源码教程资料,可以在群821460695 免费获取
'''
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)):  
    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 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 index, element in enumerate(bag):  
    print(index, element)

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 write key, pair (key, value) to dicts in.

If you are trying to access is key in dict that does not exist, may be in order to avoid KeyError wrong, 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 the 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.

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 dict comprehension.

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

Both of these methods is that they are spending big to traverse the list each time the count 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 a start point and stop point, 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 stop point 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? -5 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)
'''
更多Python学习资料以及源码教程资料,可以在群821460695 免费获取
'''
# 或者用 ranges
bag = list(range(0,10,2))  
print(bag)

This is the list of steps. list [:: 2] mean while traversing the list in a two-step extraction element.

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

10. tab key or the spacebar

Long term, the tab and spaces mix will result in a disaster, you will 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.

Guess you like

Origin blog.csdn.net/fei347795790/article/details/102741898