10 Considerations for Python development

Source: Internet
Author: User
Here are some tips and tricks that are useful in 10 python. Some of these are mistakes that are often made in the language of beginners.

Note: Let's say we're all using 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.

Click on Trey Hunner ' s tutorial for more information on the derivation of the list.

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 = Ten  # Exchanges 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 was" + name + "and I ' m" + str (age) + "years old. 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:        pri NT ("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 ran GE:      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:      PR Int ("Count 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 ("Count of {}: {}". Format (i, countr[i]))

Some reasons to use the library:

    • The code is correct and tested.


    • Their algorithms may be optimal, so they run faster.


    • Abstraction: They point to clear and document-friendly, and you can focus on those that have not yet been implemented.


    • 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))  PR Int (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.

English Original: The Python way:10 Tips

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.