pythonic_有效的python第一章pythonic思考

pythonic

I recently started to read a book “Effective Python” and I want to summarize what I learn from this book in these series of stories. First step is to study the best way to do most common things in Python which we can call it the way of Pythonic Thinking. Here is 12 steps to follow this particular style while you are programming Python.

我最近开始读一本书“ Effective Python”,我想在这一系列故事中总结从本书中学到的东西。 第一步是研究在Python中完成大多数常见事情的最佳方法,我们可以将其称为Pythonic思维方式。 在编写Python时,遵循此特定样式的以下12个步骤。

1: Know your Python

1:了解您的Python

Pythonic is an adjective that describes an approach to computer programming that agrees with the founding philosophy of the Python programming language. There are many ways to accomplish the same task in Python, but there is usually one preferred way to do it. This style is not defined by the compiler, it is defined by its user. Explicitness and simplicity are two big steps toward Pythonic thinking. Know you Python version and runtime:The runtime environment is literally python.exe or /usr/bin/python . It’s the Python executable that will interpret your Python code by transforming it into CPU-readable byte code. Popular runtimes are CPython, Jython, IronPython, PyPy, etc. Following command give you the version of your Python.$ python — version$ python3 — version (for Python3)you can also access your version of Python at runtime using sys build in module:import sysprint(sys.version_info)print(sys.version)

Pythonic是一个形容词,它描述了一种与Python编程语言的创立哲学一致的计算机编程方法。 在Python中有很多方法可以完成相同的任务,但是通常有一种首选的方法来完成它。 此样式不是由编译器定义的,而是由其用户定义的。 显式简单是通往Python思维的两个重要步骤。 了解Python版本和运行时:运行时环境实际上是python .exe或/ usr / bin / python 。 这是Python可执行文件,它将通过将您的Python代码转换为CPU可读的字节代码来对其进行解释。 流行的运行时是CPython,Jython,IronPython,PyPy等。以下命令为您提供Python版本。 $ python —版本$ python3 —版本(对于Python3),您还可以在运行时使用sys build in模块访问您的Python版本: import sysprint(sys.version_info)print(sys.version)

2: Follow the PEP8 Style Guide

2:遵循PEP8样式指南

PEP8 (Python Enhancement Proposal #8) is the style guide for how to format Python code. Minimum requirement from a code is to be valid syntax error free code but using a consistent style makes it easier to read and approachable (https://www.python.org/dev/peps/pep-0008/).1. Use space instead of tabs for indentation (4 spaces for each indenting).2. Each line must be ≤ of 79 characters.3. Continuations onto additional lines should be indented by 4 extra spaces.4. In a file, functions and classes should be separated by two blank lines.5. In a class, methods should be separated by one blank line.6. Do not put spaces around list indexes, function calls, or keyword argument assignments.7. Put one space before and after variable assignments.naming Formats of:8. Functions, variables, and attributes: lowercase_underscore9. Protected instance attributes: _leading_underscore10. Private instance attributes: __double_leading_underscore11. Classes and exceptions: CapitalizedWord12. Module-level constants: ALL_CAPS13. Instance methods in classes should use self.14. Class methods should use cls as the name of the first parameter.15. Use inline negation. Use: (if a is not b) instead (if not a is b)16. Do not check empty values by the length. Use if not list and assume empty value to be False.17. Avoid single-line if, for, while and except compound statements.18. import statements must be at top of a file.19. for relative imports: from .import (X) for absolute imports: from (Y) import (X).20. imports order: standard libraries, third-party libraries, your own modules. Each alphabetical order.

PEP8(Python增强建议#8)是有关如何格式化Python代码的样式指南。 对代码的最低要求是有效的语法无错误代码,但是使用一致的样式可以使其更易于阅读和上手( https://www.python.org/dev/peps/pep-0008/).1 。 使用空格而不是制表符进行缩进(每个缩进4个空格); 2。 每行必须≤79个字符3。 延续到其他行上应缩进4个额外空格4。 在文件中,函数和类应用两个空白行隔开5。 在一个类中,方法应该用一个空白行分隔。6。 不要在列表索引,函数调用或关键字参数赋值周围放置空格7。 在变量分配之前和之后放置一个空格。 命名格式: 8.函数,变量和属性:lowercase_underscore9。 受保护的实例属性:_leading_underscore10。 私有实例属性:__double_leading_underscore11。 类和异常:CapitalizedWord12。 模块级常量:ALL_CAPS13。 类中的实例方法应使用self.14。 类方法应使用cls作为第一个参数的名称。15 。 使用内联取反。 使用:(如果a不是b )代替(如果a不是b )16。 不要按长度检查空值。 如果未列出,请使用并假定空值为False。 17.如果forwhile和复合语句除外,请避免单行。18。 import语句必须位于文件的顶部19。 对于相对进口:从.import(X)对于绝对进口:从(Y)进口(X)。 20.导入顺序:标准库,第三方库,您自己的模块。 每个字母顺序。

3. Difference between: bytes, str, & unicode

3.区别:字节,str和unicode

There are two types of sequences of characters in Python3: I.bytes and II. str. Bytes contain raw 8-bit values and str contain unicode characters. The most common way to encode unicode character to binary data (raw 8-bit values) is UTF-8. Encode method is converting unicode to 8-bit binary data and decode is converting binary to unicode characters. The core of a program in Python3 should use unicode character(str). So, generally you may want to operate on raw 8-bit values that are UTF-8 encoded or you want to operate on unicode characters. Following can be a helper to do so:

Python3中有两种类型的字符序列:I.字节和II。 海峡字节包含原始8位值,而str包含Unicode字符。 将Unicode字符编码为二进制数据(原始8位值)的最常见方法是UTF-8 。 编码方法是将Unicode转换为8位二进制数据,而解码是将二进制转换为Unicode字符。 Python3中程序的核心应使用unicode character(str)。 因此,通常您可能希望对UTF-8编码的原始8位值进行操作,或者对Unicode字符进行操作。 以下可以帮助您做到这一点:

4. Use helper functions rather than complex expressions

4.使用辅助函数而不是复杂的表达式

Simple line expressions sounds very interesting which implement lots of logic in a single line. Use these complicated expressions in helper functions if same logic will be used repeatedly. Readability in coding is important. It is essential to simplify as much as possible whenever you can. One useful hint on this matter is to use if/else rather than Boolean operators like or and and in expressions.

简单的行表达式听起来很有趣,可以在一行中实现很多逻辑。 如果将重复使用相同的逻辑,请在辅助函数中使用这些复杂的表达式。 编码中的可读性很重要。 尽可能地简化是至关重要的。 关于此问题的一个有用提示是使用if / else而不是布尔表达式(orand和in)。

5. Slicing sequences

5.切片顺序

The most basic slicing is: list[start:end] (note: start is inclusive and end is exclusive)- Note: when you slice from start, a[0:3], leave out 0 for less visual noise: a[:3]- Note: similar for ending: a[3:]- Note: negative numbers can be used for offsets relative to the end.a[-10:] = last 10 itemsa[:10] = first 10 itemsNote: a[-n:] will work when n > 1. When n = 0, a[-0:] will give you a copy of the original list.list[start:end:stride]: Python has stride syntax which lets you take every nth item. Consider to use strides only when it is needed.For example: odds: a[::2] evens: a[1::2]Note: a[::-1] reversing a byte string

最基本的切片是: list [start:end] (注意:start是包含在内的,而end是排他的)-注意:当您从开始切片a [0:3]时,请留出0以减少视觉噪声:a [: 3]-注意:与结尾类似:a [3:]-注意:负数可用于相对于结尾的偏移量。a[-10:] =后10个项a [:10] =前10个项注意:a [ -n:]在n> 1时有效。当n = 0时,a [-0:]将为您提供原始列表的副本。 list [start:end:stride] :Python具有跨步语法,可让您获取第n个项目。 考虑仅在需要时才使用跨步。例如:odds:a [:: 2]偶数:a [1 :: 2]注意:a [::-1]反转字节字符串

6. Use List comprehensions instead of map and filter

6.使用列表推导而不是地图和过滤器

List comprehensions provide syntax for deriving one list from another. For instance,a = [1, 2, 3, 4]squares = [x**2 for x in a] → [1, 4, 9, 16]List comprehensions are more clear generally than the map built-in functions. map requires creating lambda function for the computation:square = map(lambda x: x**2, a)Unlike map, list comprehensions let you to do filtering or adding conditions:even_squares = [x**2 for x in a if x % w == 0 ] → [4, 16]Built-in filtering function in map would be more complicated:alt = map(lambda x: x**2, filter(lambda x: x%2 == 0,a))assert even_squares == list(alt)Equivalent of list comprehensions for dictionaries and sets can be used like:hero_ranks = {‘Batman’: 1, ‘Superman’: 2, ‘Spiderman’:3}rank_dic = {rank: name for name, rank in hero_ranks.item()}hero_len_set = {len(name) for name in rank_dic.values()}List comprehensions supports multiple levels of looping:a = [[1,2,3],[1,2,3],[1,2,3]]a_flat = [x for row in a for x in row] → [1,2,3,1,2,3,1,2,3]

列表推导提供了从另一个列表派生一个列表的语法。 例如, a = [1、2、3、4]正方形= [a中x的x ** 2]→[1、4、9、16]列表推导通常比地图内置函数更清晰。 map需要为计算创建lambda函数: square = map(lambda x:x ** 2,a)与map不同,列表推导使您可以进行过滤或添加条件: even_squares = [x ** 2 for if in x %w == 0]→[4,16] map中的内置过滤功能会更加复杂: alt = map(lambda x:x ** 2,filter(lambda x:x%2 == 0,a) )assereven_squares == list(alt)可以等效使用字典和集合的列表理解,例如: hero_ranks = {'蝙蝠侠':1,'超人':2,'蜘蛛侠':3} rank_dic = {rank:名称,在hero_ranks.item()中的排名} hero_len_set = {在rank_dic.values()中为名称的len(name)}列表推导支持多个循环级别:a = [[[1,2,3],[1,2, 3],[1,2,3]] a_flat = [x对于a中的x对于行中的x]→[1,2,3,1,2,3,1,2,3]

7. Use generator expressions for large comprehensions

7.使用生成器表达式进行大范围的理解

List comprehensions create a whole new list for each item in input which would be fine for smaller input size but for large inputs can cause problems using significant amounts of memory. To solve this issue, generator expression can be used which does not materialize the whole output sequence when they are run. Instead, generator expressions evaluate to an iterator that yields one item at a time from the expression.A generator expression is created by putting list-comprehension-like syntax between ( ) characters.value = [len(x) for x in open(‘/tmp/my_file.txt’)]: List comprehensionvalue = (len(x) for x in open(‘/tmp/my_file.txt’)): generator expression

列表推导会为输入中的每个项目创建一个全新的列表,这对于较小的输入大小会很好,但是对于较大的输入,可能会使用大量内存而导致问题。 要解决此问题,可以使用生成器表达式,该表达式在运行时不会具体化整个输出序列。 取而代之的是,生成器表达式求值一个迭代器,该迭代器一次从该表达式中产生一项。生成器表达式是通过在()字符之间放置类似于列表理解的语法来创建的。 value = [open('/ tmp / my_file.txt')中x的len(x)]:列表理解值=(open('/ tmp / my_file.txt')中x的len(x)):生成器表达式

8. Prefer enumerate over range

8.最好列举范围

The range built-in function is useful for loops that iterate over a set of integers. When you have a data structure to iterate over, like a list of strings, you can loop directly over the sequence.var1 = [] a listfor var in var1: …But then sometimes you want to iterate over a list and also know the index of the current item in the list. One obvious way to do that is to use range. Use a for loop over the range of the length of the list and take index rank this way. To improve this case, Python provides the enumerate built-in function. So again let say var1 is a list and we want to iterate over its items and take their index ranks. To do so:for i, var in enumerate(var1): …So now i is the orders and var are items. You can specify the order you want to start with in the list by enumerate(var1,1).

范围内建函数对于循环访问一组整数的循环很有用。 当您有一个要遍历的数据结构(如字符串列表)时,可以直接在序列上循环。 var1 = [] var1中var的列表:…但是有时您想遍历列表,并且还知道列表中当前项目的索引。 一种明显的方法是使用范围。 在列表的长度范围内使用for循环,并以此方式进行索引排名。 为了改善这种情况,Python提供了枚举内置函数。 再次让我们说var1是一个列表,我们想遍历其项并取得其索引等级。 这样做:对于我来说,enumerate(var1)中的var:…因此,现在是订单,而var是项目。 您可以通过enumerate(var1,1)在列表中指定要开始的顺序

9. Using Zip to process iterators in parallel

9.使用Zip并行处理迭代器

In Python3, zip wraps two or more iterators with a lazy generator. The zip generator yields tuples containing the next value from each iterator. The resulting code is much cleaner than indexing into multiple lists. There is one problem with the zip built-in for Python3. It behaves strangely if the input iterators are of different lengths.

在Python3中, zip用惰性生成器包装两个或多个迭代器。 zip生成器生成包含每个迭代器下一个值的元组。 生成的代码比索引到多个列表要干净得多。 Python3内置的zip存在一个问题。 如果输入迭代器的长度不同,它的行为会很奇怪。

10. Avoid else blocks after for and while loops

10.避免在for和while循环之后使用else块

Python loops have an extra feature that is not available in most other programming languages. You can put an else block immediately after a loop’s repeated interior block. The else block runs after the loop finishes. Note that using a break statement in a loop will actually skip the else block. Also the else block runs when while loops are initially false or for loops over empty sequence. Although it is a cool option but is better not to use else blocks after loops because their behavior is not intuitive and can be confusing.

Python循环具有其他大多数编程语言所没有的额外功能。 您可以在循环重复的内部块之后立即放置else块。 else块在循环结束后运行。 注意,在循环中使用break语句实际上将跳过else块。 当while循环最初为false或for循环为空序列时 else块也会运行。 尽管这是一个很不错的选择,但最好不要在循环后使用else块,因为它们的行为不直观,而且会造成混乱。

11. Take advantage of try/finally blocks

11.利用try / finally块

Use try/finally when you want exceptions to propagate up, but you also want to run cleanup code even when exceptions occur. One example can be usage of this block for opening and reliably closing file handles. For example:handle = open(file)try: data= …finally: handle.close()

当您希望异常传播时,请使用try / finally ,但即使发生异常,也要运行清除代码。 一个示例可以是使用此块来打开和可靠地关闭文件句柄。 例如: handle = open(file)try:data =…finally:handle.close()

12. Take advantage of try/except/else blocks

12.利用try / except / else块

Use try/except/else to make it clear which exceptions will be handled by your code and which exceptions will propagate up. When the try block does not raise an exception, the else block will run. This block combination minimize the amount of code and improve readability. It is also possible to use try/except/else/finally when we want to have it all in one compound statement.The try/finally compound statement lets you run cleanup code regardless of whether exceptions were raised in the try block. The else block helps you minimize the amount of code in try blocks and visually distinguish the success case from the try/except blocks. An else block can be used to perform additional actions after a successful try block but before common cleanup in a finally block.

使用try / except / else可以清楚地知道哪些异常将由您的代码处理以及哪些异常将向上传播。 当try块未引发异常时, else块将运行。 这种块组合可最大程度地减少代码量并提高可读性。 当我们希望将所有内容都包含在一个复合语句中时,也可以使用try / except / else / finally。try / finally复合语句使您可以运行清除代码,而不管try块中是否引发了异常。 else块可帮助您最小化try块中的代码量,并在视觉上将成功案例与try / except块区分开。 在成功的try块之后但在finally块中的常规清理之前, else块可用于执行其他操作。

翻译自: https://medium.com/the-innovation/effective-python-chapter-i-pythonic-thinking-8ac561c8184c

pythonic

你可能感兴趣的:(python)