10 tips and tips for Python Development

Source: Internet
Author: User

10 tips and tips for Python Development

Note: In this article, we assume that we use Python 3.

1. List Derivation

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

Now you want to double all elements and make them look like this: [2, 4, 6, 8, 10]

Most beginners will probably do 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 are better methods:

bag = [elem * 2 for elem in bag]

Very concise, right? This is called the list derivation of Python.

2. traverse the list

Continue, or the list above.

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 do not need to index each element, but if you want to do so, useenumerateFunction. It looks like below:

bag = [1, 2, 3, 4, 5] for index, element in enumerate(bag):  print(index, element)

It is very intuitive and clear.

3. Element swapping

If you switch from java or C to Python, you may get used to this:

A = 5 B = 10 # exchange a and btmp = a = B = tmp

But Python provides a more natural and better method!

A = 5 B = 10 # exchange a and ba, B = B,

Pretty?

4. Initialization list

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

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

In another way:

bag = [0] * 10

Look, more elegant.

Note:If your list contains a list, this will produce a small 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 are changed, and we just want to change the first list.

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]]

Remember:

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

5. Construct a string

You often need to print strings. If there are many 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)

Well, how messy is this? You can use a pretty and concise method instead, .format .

In 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 (tuples)

Python allows you to return multiple elements in a function, which makes life easier. However, the following common errors occur when the tuples are unwrapped:

def binary():  return 0, 1result = binary() zero = result[0] one = result[1]

This is unnecessary. You can replace it with this:

def binary():  return 0, 1zero, one = binary()

If you want all elements to be returned, use an underscore _:

zero, _ = binary()

This is so efficient!

7. Access Dicts (dictionary)

You will also write frequently to dictskey,pair(Key, value ).

If you try to accessdictOfkeyTo avoidKeyErrorErrors:

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(10):  if i in countr:  print("Count of {}: {}".format(i, countr[i])) else:  print("Count of {}: {}".format(i, 0))

Howeverget()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) + 1for i in range(10):  print("Count of {}: {}".format(i, countr.get(i, 0)))

You can also usesetdefault.

This also uses a simpler but more costly 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)))

You can also usedictDerivation.

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

These two methods have a high overhead because theycountThe list will be traversed when called.

8. database used

You only need to import the existing database to do what you really want.

In the preceding example, we create a function to count the number of times a number appears in the list. So there is already a library to do this.

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 database usage reasons:

1. The code is correct and tested.

2. Their algorithms may be optimal, so they can run faster.

3. Abstraction: they point to clarity and are 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 recreate the wheel.

9. Slice/step in the list

You can specifystartPoints andstopPoint, just like thislist[start:stop:step] .

Let's take out the first 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 the slice.stopPoint is 5, and 5 elements are extracted from the list before being stopped.

What if the last five elements are used?

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

Don't you understand? -5 indicates that five elements are extracted from the end of the list.

If you want to operate the element interval in the list, you may do the following:

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 use rangesbag = list (range (0, 10, 2) print (bag)

This is the step in the list.list[::2]This means to retrieve an element from the list in two steps at the same time.

You can uselist[::-1]Cool flip list.

10. The tab key or space key

For a long time, mixing tabs and spaces will cause a disaster and you will seeIndentationError: unexpected indent. Whether you select the tab or space key, you should keep using it in your files and projects.

The reason for using spaces instead of tabs is that tabs are not the same in all editors. For the editor used, the tab may be treated as two to eight spaces.

You can also use spaces to define tabs when writing code. In this way, you can use several spaces as tabs. Most Python users use four spaces.

Summary

The above are the tips you should pay attention to during Python development. I hope it will be helpful for you to learn and use python. If you have any questions, please leave a message.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.