From translator
I present to your attention the translation of the article
“Be Pythonic” by Shalabh Chaturvedi recommended in
this topic. If my undertaking is supported, I also plan to translate the other two articles of this author mentioned there.
Introduction
This article is intended for beginners in Python.
When moving from one language to another, some things may not be
known to you (see
Transfer of Learning ). What you know about other languages may not always be useful in Python. This article contains some of the idioms used in Python that I especially like. I hope readers will find them useful for mastering the language.
')
Counters are rarely needed, iterators only occasionally.
Wrong:
i = 0 while i<10: do_something(i) i += 1
Right:
for i in xrange(10): do_something(i)
In the following example, the program goes through the list.
Wrong:
i = 0 while i<len(L): do_something(L[i]) i += 1
Right:
for item in L: do_something(item)
Iterators are useful when you want to keep a position in a loop between two runs:
itrL = iter(L) for item in itrL: do_something(item) if is_some_condition(item): break for item in itrL: # , do_something_else(item)
Maybe you don't need a for loop.
Python provides many higher-level tools for working with sequences, such as zip (), max (), min (),
list comprehensions ,
generator expressions , etc. These and other functions are described. in the
“Built-in Functions” section of the documentation.
You can store data in tuples, lists, dictionaries and work with whole sets. For example, here's an example of code that reads a CSV file (in which the first line contains field names), converts each line into a dictionary element and counts the sum of the numbers in the “quantity” column.
f = open('filename.csv') # f — field_names = f.next().split(',') # next() records = [dict(zip(field_names, line.split(','))) for line in f] # print sum(int(record['quantity']) for record in records)
In any case, you should use the
csv module included in the Python Standard Library, but this example illustrates some useful features. Using zip () and dict (), you can combine a tuple of names and a tuple of values and get a dictionary. And in combination with the generation of lists, you can do it with a whole list in one step.
A tuple is not a list that cannot be edited.
The contents of the tuple are usually
heterogeneous , for example, (first_name, last_name) or (ip_address, port). In this case,
the data
type can be the same (both first_name and last_name are strings). You can think of a tuple as a row in a relational database — in fact, a row of a table is even called a tuple in the formal description of a relational model. In contrast, a list of names is always a list.
Unpacking tuples is a useful way to extract items from them. For example:
for (ip_address, port) in all_connections: if port<2000: print 'Connected to %s on %s' % (ip_address, port)
This code shows that all_connections is a list (or an iterable object) containing tuples of the form (ip_address, port). This is better than using for item in all_connections and calling an item through item [0] or in a similar way.
It is also worth using unpacking tuples if the function should return multiple values:
# name, ext = os.path.splitext(filename)
Classes are not intended to group functions.
C # and Java allow you to place code only in classes, so they have a lot of
utility classes that contain only static methods. For example, these are mathematical functions, such as sin (). In Python, you simply use a module containing top-level functions.
Say no to getters and setters
Yes,
encapsulation is important. But getters and setters are not the only way to do this. In Python, you can use
property instead of class members, that is, completely change the encapsulation method without changing the code that uses the class.
Functions are objects
A function is an object that can be called. This example sorts the list of dictionaries by the value corresponding to the 'price' key:
# , def get_price(ob): return ob['price'] L.sort(key=get_price) # , ['price'] * This source code was highlighted with Source Code Highlighter.
You can also use sorted (L, key = get_price) to get a new list instead of changing the existing one.
Related Links
Python is not javaWhat is pythonic