Original book reference: http://www.jeffknupp.com/blog/2012/10/04/writing-idiomatic-python/
Previous: Translation "Writing idiomatic Python" (ii): function, exception
Next article: To be UPDATED.
2.1 Variable 2.1.1 Use chained assignments to make statements concise when assigning the same value to multiple variables
Python supports chained assignments so that multiple variables can be set to the same value in a single chained assignment, which makes the statement more concise.
Bad style:
1 ' Foo ' 2 ' Foo ' 3 ' Foo '
Authentic Python:
1 ' Foo '
2.1.2 Avoid using temporary variables for value exchange
There is absolutely no need to use an extra temporary variable for value exchange in Python. The use of tuples is not only convenient but also more readable.
Bad style:
1 ' Foo ' 2 ' Bar ' 3 temp = foo4 foo = bar5 bar = Temp
Authentic Python:
1 ' Foo ' 2 ' Bar ' 3 (foo, bar) = (bar, foo)
2.2 String 2.2.1 String-related functions use chained calls to make intent more concise
When a series of processing is performed on a string of data, it is often more explicit and straightforward to take the next call directly after the last call than to create a series of temporary variables. Of course, if too many chained calls can break the readability, it is generally better to use a chained call if the operation is not more than three.
Bad style:
1 ' The three Musketeers:alexandre Dumas ' 2 formatted_book_info = book_info.strip ()3 formatted_book_info = Formatted_book_ Infor.upper ()4 formatted_book_info = Formatted_book_infor.replace (':') 'by')
Authentic Python:
1 ' The three Musketeers:alexandre Dumas ' 2 formatted_book_info = Book_info.strip (). Upper (). Replace (':'by ')
2.2.2 Use the string element in the Join connection list
This is faster, consumes less memory, and this usage is very common in python. Note that the following example uses a "connection string", which can be replaced with the delimiter you want when you actually use it.
Bad style:
1 result_list = ['True' 'False'File Not found']2"3 for in result _list:4 result_string + = result
Authentic Python:
1 result_list = ['True' 'False'File Not found']2". Join (Result_list)
2.2.3 uses Ord to get the ASCII code of the character, using CHR to get the character from the ASCII code
Getting the ASCII code of a character is a useful feature (such as String hashing), and it is often useful to get the corresponding character from ASCII.
Python provides two built-in functions,CHR and Ord, that enable the conversion of characters and ASCII code to one another.
Bad style:
1Hash_value =02Character_hash = {3 'a': 97,4 'b': 98,5 'C': 99,6 # ...7 'y': 121,8 'Z': 122,9 }Ten forEinchsome_string: OneHash_value + =Character_hash[e] A returnHash_value
Authentic Python:
1 hash_value = 02 for in some_string:3 Hash_value + ord (e)4return hash_value
2.2.4 using the Format function for string formatting
In general, there are three ways to format strings: The simplest, but the least recommended, is to use the + to concatenate strings. Another way is the old-fashioned way of formatting strings using%, which can be seen in many other languages, such as printf in some languages. This method is better than using the + method.
In Python, the most authentic and clear usage is to format strings using the Format function. Similar to the old format method, this approach uses a formatted string as a template and uses some value substitution placeholders to generate the final string. Better than the old format method, in the Format function, We can name the placeholder, get the property of the corresponding variable of the placeholder, control the character width and padding, and so on. The Format function makes the formatting of strings concise.
Bad style:
1 defGet_formatted_user_info_worst (user):2 #tedious to type and prone to conversion errors3 return 'Name:'+ User.Name +', Age:'+ STR (user.age) +', Sex:'+User.sex4 5 defget_formatted_user_info_slightly_better (user):6 #No visible connection between the format string placeholders7 #And values to use . Also, why does I have a to know the type?8 #Don ' t These types all has __str__ functions?9 return 'Name:%s, Age:%i, Sex:%c'% (User.Name, user.age, User.sex)
Authentic Python:
1 defget_formatted_user_info (user):2 #Clear and concise. At a glance I can tell exactly what3 #The output should be. Note:this string could be returned4 #directly, but the string itself was too long to fit on the5 #page.6Output ='Name: {user.name}, Age: {user.age}, Sex: {user.sex}'. Format (user=user)7 returnOutput
2.3 List 2.3.1 Using list resolution to generate a new list from a list
In the case of proper use, list parsing increases the clarity of the code from creating a new list in a list. This is especially true when the newly created list is a transformation of the source list or a condition check.
In addition to making the code clearer, list parsing is highly efficient in execution (CPython).
Bad style:
1 some_other_list =range (2 )some_list = list ()3for in some_other_list:4 if is_prime (Element):5 some_ List.append (element + 5)
Authentic Python:
1 some_other_list = range (Ten)2forif is_prime (Element)]
2.3.2 using negative subscript
One feature that is often overlooked by many Python starters is that a negative subscript can be used in Python lists and strings. and positive subscript are different from the beginning of the list, and the subordinate subscript is the number of backwards from the end of the list.
Bad style:
1 def Get_suffix (word): 2 Word_length = len (word)3 return word[word_length-2:]
Authentic Python:
1 def Get_suffix (word): 2 return word[-2:]
2.3.3 and the built-in map () and filter () functions prioritize the use of list parsing
Python is a language that has been evolving since its inception. Because of this, there has been some history left behind. The map and filter functions are examples, although in some cases it is best to use map and filter , but now almost all of them can be replaced with list parsing. And the readability and clarity of the list parsing is better, so at least in my book I think it's preferable to use list parsing instead of a combination of map and filter .
Bad style:
1 the_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, ten]2def is_odd (number):3
return number% 2 = =1 4 odd_numbers = filter (is_odd, the_list)5 Odd_numbers_ Times_two = List (map (lambda x:x * 2, Odd_numbers))
Authentic Python:
1 the_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, ten]2for inif n 2 = = 1]
In fact, this is a very matter of opinion, there are a lot of stackoverflow on the Map/filter and list comprehension controversy, in terms of efficiency, for different circumstances, the two ways to win each other, In terms of readability, I actually think map and filter are much better than list comprehension. And don't forget that there's a function called reduce.
2.3.4 sums the elements in a list using the built-in sum function
This may seem odd to some who have already used the sum of their habits. For more novice python, however, what they do is they re-implement the sum function. If a function is already built-in, then we should not reinvent the wheel.
Bad style:
1 the_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, ten]2 the_sum = 03forin< /c6> the_list:4 the_sum + = element
Authentic Python:
1 the_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, ten]2 the_sum = SUM (the_list)
2.3.5 use all to check whether all elements are true in a traversal structure
Like sum , all is a built-in function that is frequently rewritten by novices. It checks to see if an element in a traversal structure is true.
Bad style:
1 def Contains_zero (iterable): 2 for inch iterable: 3 if e = = 0:4 return True5 return False
Authentic Python:
1 def Contains_zero (iterable): 2 # 0 is "falsy," so this works 3 return Not all (iterable)
2.3.6 prefer to use xrange instead of range, unless you need a list of range builds
Both xrange and range allow you to iterate through a list of values. The difference is thatxrange no longer stores a complete list in memory. In most cases, the two will not be used in real time, but when you need to traverse a very large range of values, you can see a big difference in memory usage and execution efficiency.
Bad style:
1 # a loop over A large range this breaks out 2 # early:a Double whammy! 3 even_number = int ()4 for in range (1000000):5 if index% 2 = = 0:6 even_number = index7 break
Authentic Python:
1 even_number = int ()2 for in xrange (1000000):3 if index% 2 = = 0:4 even_number = index5 break
Reprint Please specify source: Wen XI @ Blog Park
Previous: Translation "Writing idiomatic Python" (ii): function, exception
Next article: To be UPDATED.
Writing idiomatic Python (three): variables, strings, lists