Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What practical skills you need to know to get started with Python

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

In this issue, the editor will bring you what practical skills you need to know about the introduction to Python. The article is rich in content and analyzes and narrates it from a professional point of view. I hope you can get something after reading this article.

Mainly record some common skills in Python

Python Zen

This is the guiding principle of Python, but it has different interpretations.

If you use a programming language named after the sketch comedy art troupe, you have a sense of humor.

Beauty is better than ugliness.

Clarity is better than implication.

Simple is better than complex.

Flat is better than nesting.

Sparse is better than dense.

Special circumstances cannot be special enough to break the rules.

Mistakes should not be passed on silently.

.

Code style: improve readability

Programs must be written for people to read, and only incidentally for machines to execute.

-Abelson & Sussman, Structure and Interpretation of Computer Programs

PEP 8: a guide to Python code style

It is worth reading:

Http://www.python.org/dev/peps/pep-0008/

Spaces (lines) use (1)

◆ uses four spaces to indent.

Do not use tabs for ◆.

◆ do not mix tabs and spaces.

Both ◆ IDEL and Emacs's Python support spaces mode.

◆ there should be a blank line between each function.

◆ there should be two blank lines between each Class.

Spaces (lines) use (2)

◆ should add a space before "," when using a dictionary (dict), list (list), tuple (tuple), and parameter (argument) list, and when using a dictionary (dict), add a space after the ":" sign instead of before it.

◆ does not add spaces before parentheses or parameters.

◆ should have no spaces before and after the document comments.

Python code

Def make_squares (key, value=0): "Return a dictionary and a list..." D = {key: value} l = [key, value] return d, l

Naming

◆ joined_lower can be function name, method name, attribute name

◆ joined_lower or ALL_CAPS is constant

◆ StudlyCaps Class name

◆ camelCase can only be used in predefined naming conventions

◆ attribute: interface, _ internal, _ _ private

◆ can avoid the _ _ private form as much as possible. The following two links explain why there is no private declaration in python?

Http://stackoverflow.com/questions/70528/why-are-pythons-private-methods-not-actually-private

Http://stackoverflow.com/questions/1641219/does-python-have-private-variables-in-classes

Longer lines of code

Keep one line of code at 80 characters long.

Use the implied line continuation in parentheses:

Python code

Def _ init__ (self, first, second, third, fourth, fifth, sixth): output = (first + second + third + fourth + fifth + sixth)

Or use\ where a line break is needed to continue the line:

Python code

VeryLong.left_hand_side\ = even_longer.right_hand_side ()

In addition, using a backslash is risky, and if you add a space after the backslash, it goes wrong. In addition, it makes the code ugly.

Longer string

The practice of concatenating adjacent strings:

Python code

> print 'o'n' "e" one

Although spaces between characters are not required, it helps with readability.

Python code

> print 't'r'\ /\ /'"" o "t\ /\ / o"

A string that begins with an "r" is a string of "raw" (similar to the escape character in java). The above backslash is treated as a normal string. They are very useful for regular expressions and Windows file system paths.

Note: you cannot connect in the above way using string variable names.

Python code

> a = 'three' > b =' four' > a b File ", line 1 a b ^ SyntaxError: invalid syntax

This is because automatic concatenation is handled by the Python parser / compiler, because it cannot "translate" variable values at compile time, so variables must be concatenated using the "+" operator at run time.

Compound statement

Good:

Python code

If foo = 'blah': do_something () do_one () do_two () do_three ()

Bad:

Python code

If foo = 'blah': do_something () do_one (); do_two (); do_three ()

Documentation comments (Docstrings) & comments

Documentation comments = used to explain how to use code

Document Notes Convention: http://www.python.org/dev/peps/pep-0257/

Comment = Why (reason) & how the code works, such as:

Python code

#! BUG:... #! FIX: This is a hack #? Why is this here?

Annotations are already the most basic thing for any language developer, so I won't go into details here.

Exchange variable

The practice of exchanging variables in other languages is generally:

Java code

Temp = an a = b b = temp

What Python does:

Python code

B, a = a, b

Maybe you've seen this before, but do you know how it works?

◆ first, a comma is a tuple construction syntax.

To the right of the ◆ equal sign is to define a tuple (tuple packing).

To the left of the ◆ is a target tuple (tuple unpacking).

The tuple on the right is unpacked to the ungrouped on the left by name.

For more information on the unpacked example:

Python code

> info = ['David',' Pythonista','+ 1250'] > > name, title, phone = info > name 'Davids' > title' Pythonista' > phone'+ 1250'

Use loops on structured data:

Info is a list defined above. So the following people has two items, both of which are list with three items each.

Python code

> people = [info, ['Guido',' BDFL', 'unlisted'] > for (name, title, phone) in people:. Print name, phone... David + 1250 Guido unlisted

In the above loop, two items in people (list item) have been unpacked into (name, title, phone) ungrouped.

Can be nested at will (as long as the structures on the left and right sides must match):

Python code

> > david, (gname, gtitle, gphone) = people > gname 'Guido' > gtitle' BDFL' > gphone 'unlisted' > david [' David', 'Pythonista',' + 1250']

More about Tuples

What we see is tuples constructed by commas, not parentheses. For example:

Python code

> 1, (1,)

Python's interpreter will display parentheses for you, so it is recommended that you use parentheses:

Python code

> (1,)

Never forget the comma!

Python code

> > (1) 1

In tuples with only one element, trailing commas are required, and in tuples with 2 + elements, trailing commas are optional. If you create a 0 or empty tuple, a pair of parentheses is a shortcut syntax:

Python code

> () > tuple () ()

A common mistake when you do not want to be ungrouped, but inadvertently add a comma, it is easy to cause errors in your code, such as:

Python code

> value = 1, > > value # is a tuple, not an int (1,)

So, when you find a tuple, go and find that number.

About "_"

Is a very useful feature, but few people know about it.

When you evaluate an expression or call a function in interactive mode (such as IDEL), the result must be a temporary name, _ (underscore):

Python code

> 1 + 1 2 > 2

Stores the value of the * output in _.

When the result of the output is None or there is no output, the value of _ does not change, and the last value is still saved. This is where the convenience lies.

Of course, this can only be used in interactive mode and cannot be supported in modules.

This is very useful in interactive mode when you do not save the calculation results during the process or you want to see the output of the one-step execution:

Python code

> import math > math.pi / 3 1.0471975511965976 > angle = _ > > math.cos (angle) 0.500000000000011 > > _ 0.5000000000011

Create String: create from list

Start defining a string list:

Python code

Colors = ['red',' blue', 'green',' yellow']

When we need to concatenate the above list into a string. Especially when list is a large list.

Don't do this:

Python code

Result =''for s in colors: result + = s

This approach is very inefficient, it has terrible memory usage problems, as for why, if you are javaer, the string connection, I think you are no stranger.

Instead, you should do this:

Python code

Result = '.join (colors)

When you only have dozens or hundreds of string items connected, they don't make much difference in efficiency. But you have to get into the habit of writing efficient code, because join can improve the performance of for connections compared to thousands of strings.

If you need to use a function to generate a list of strings, you can also use:

Python code

Result = '.join (fn (I) for i in items)

Use as much as possible

Good:

Python code

For key in d: print key

◆ 's use of in is generally very fast.

The ◆ approach also applies to other container objects (such as list,tuple and set).

◆ in is the operator (as you can see above).

Bad:

Python code

For key in d.keys (): print key

To maintain consistency with the above, use use key in dict instead of dict.has_key ():

Python code

# do this: if key in d:... do something with d [key] # not this: if d.has_key (key):... do something with d [key]

Get function in Dictionary

We often need to initialize the data in the dictionary:

Here are some bad ways to implement it:

Python code

Navs = {} for (portfolio, equity, position) in data: if portfolio not in navs: navs [portfolio] = 0 navs [portfolio] + = position * prices [equity]

Use dict.get (key, default) to delete the if judgment code:

Python code

Navs = {} for (portfolio, equity, position) in data: navs [portfolio] = (navs.get (portfolio, 0) + position * prices [equity])

This approach is more straightforward.

Setdefault function in Dictionary (1)

When we want to initialize the value of a variable dictionary. The value of each dictionary will be a list. Here are some bad practices:

Initialize the value of the variable dictionary:

Python code

Equities = {} for (portfolio, equity) in data: if portfolio in equities: equivalents [portfolio] .append (equity) else: equities [portfolio] = [equity]

Make this code work better through dict.setdefault (key, default):

Python code

Equities = {} for (portfolio, equity) in data: equities.setdefault (portfolio, []) .append (equity)

Dict.setdefault () is equivalent to "get, or set & get" or "if not, set"; if your dictionary Key is a complex computational or long type, using setdefault is particularly effective.

Setdefault function in Dictionary (2)

The setdefault dictionary method we saw can also be used as a separate statement:

Python code

Avs = {} for (portfolio, equity, position) in data: navs.setdefault (portfolio, 0) navs [portfolio] + = position * prices [equity]

We ignore the default value returned by the dictionary's setdefault method here. We are taking advantage of the role in setdefault, which is only set when there is no value of key in dict.

Create & split Dictionary

If you have two list objects, you want to build a dict object from these two objects.

Python code

Given = ['John',' Eric', 'Terry',' Michael'] family = ['Cleese',' Idle', 'Gilliam',' Palin'] pythons = dict (zip (given, family)) > > pprint.pprint (pythons) {'John':' Cleese', 'Michael':' Palin', 'Eric':' Idle', 'Terry':' Gilliam'}

Similarly, if you want to get two lists, it is also very simple:

Python code

> pythons.keys () ['John',' Michael', 'Eric',' Terry'] > pythons.values () ['Cleese',' Palin', 'Idle',' Gilliam']

It is important to note that although the above list is ordered, the keys and values in dict are unordered, which is precisely because dict is unordered in nature.

Index & item (1)

If you need a list, here is a lovely way to save your typing:

Python code

> items = 'zero one two three'.split () > print items [' zero', 'one',' two', 'three']

If we need to traverse this list, and we need index and item:

Python code

-or-I = 0 for item in items: for i in range (len (items)): print I, item print i, items [I] I + = 1

Index & item (2): enumerate

You can return the (index, item) tuple in list through enumerate:

Python code

> print list (enumerate (items)) [(0, 'zero'), (1,' one'), (2, 'two'), (3,' three')]

As a result, it is easier to get index and item by traversing list:

Python code

For (index, item) in enumerate (items): print index, item

Python code

# compare: # compare: index = 0 for i in range (len (items)): for item in items: print I, items [I] print index, item index + = 1

It is not difficult to see that using enumerate is simpler and easier to read than the following two ways, which is exactly what we want.

Here is an example of how to return an iterator through enumerate:

Python code

> enumerate (items) > e = enumerate (items) > e.next () (0, 'zero') > e.next () (1,' one') > e.next () (2, 'two') > e.next () (3,' three') > e.next () Traceback (most recent call last): File ", line 1, in? StopIteration

Default parameter valu

This is a common mistake for beginners, even for some senior developers, because they don't know names.

Python code

Def bad_append (new_item, averse list = []): a_list.append (new_item) return a_list

The problem here is that a_list is an empty list, and the default value is initialized when the function is defined. Therefore, each time you call this function, you will get a different default value. Several attempts were made:

Python code

> print bad_append ('one') [' one'] > print bad_append ('two') [' one', 'two']

Lists are mutable objects, and you can change their contents. The correct way is to first get a default list (or dict, or sets) and create it at run time.

Python code

Def good_append (new_item, a_list=None): if a_list is None: await list = [] a_list.append (new_item) return a_list

Judge True value

Python code

# do this: # not this: if x: if x = = True: pass pass

Its advantage lies in efficiency and elegance.

Judge a list:

Python code

# do this: # not this: if items: if len (items)! = 0: pass pass # and definitely not this: if items! = []: pass

True value

True and False are instances of Boolean values of the built-in bool type. Everyone has only one example.

FalseTrueFalse (= 0) True (= = 1) "(empty string) any string but"(", "anything") 0, 0.0any number but 0 (1,0.1,-1,3.14) [], (), {}, set () any non-empty container ([0], (None,), [']) Nonealmost any object that's not explicitly False

Simple is better than complex.

Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.

-Brian W. Kernighan

These are the practical skills that you need to know about the introduction to Python that you share. If you happen to have similar doubts, you might as well refer to the above analysis to understand. If you want to know more about it, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 268

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report