Because of the simplicity of the language, Python allows us to write code in a human way of thinking. It is easier for novices to learn, and veterans love it even more.
To write Pythonic (elegant, authentic, and tidy) code, you also need to observe the big cow codes. Here, Ming Ge has collected some common Pythonic writing methods to help you develop the habit of writing excellent code.
Exchanging the values of two variables, you normally want to use an intermediate temporary variable to transition.
tmp = a
a = b
b = tmp
Can be solved with one line of code (and does not affect readability), never need three lines of code.
a,b = b,a
Below is a very simple for loop.
my_list =[]for i inrange(10):
my_list.append(i*2)
In a for loop, if the logic is relatively simple, it is better to try the list comprehension of the list. Although there is only one line of code, the logic is clear.
my_list =[i*2for i inrange(10)]
In the above two cases, multiple lines of code were written into one line of code in another way.
This does not mean that the fewer lines of code, the more Pythonic.
For example, writing like this is not recommended.
print('hello');print('world')if x ==1:print('hello,world')if<complex comparison> and <other complex comparison>:
# do something
The suggestion is to follow the following wording
print('hello')
print('world')
if x ==1:print('hello,world')
cond1 =<complex comparison>
cond2 =<other complex comparison>if cond1 and cond2:
# do something
When using a for loop, how to get the corresponding index, beginners are used to using the range + len function
for i inrange(len(my_list)):print(i,"-->", my_list[i])
A better approach is to use the built-in function enumerate
for i,item inenumerate(my_list):print(i,"-->",item)
Use *
to unpack a list
a,*rest =[1,2,3]
# a =1, rest =[2,3]
a,*middle, c =[1,2,3,4]
# a =1, middle =[2,3], c =4
If all the elements in a list (or iterable object) are string objects and want to connect them, the usual approach is
letters =['s','p','a','m']
s=""forletin letters:
s +=let
The more recommended approach is to use the join function
letters =['s','p','a','m']
word =''.join(letters)
To judge whether a variable is true (false), novices are used to directly use ==
to compare with True, False, None
if attr == True:print('True!')if attr == None:print('attr is None!')
In fact, containers without any elements such as ""
, []
, and {}
are all false values. You can directly use if not xx
to judge.
if attr:print('attr is truthy!')if not attr:print('attr is falsey!')
When directly using []
to access the elements in the dictionary, if the key does not exist, an exception will be thrown, so the new club may first determine whether there is this key, and then take it.
d ={'hello':'world'}if d.has_key('hello'):print(d['hello']) # prints 'world'else:print('default_value')
The more recommended way is to use get
to get it, if there is no such key, it will return None by default (of course you can also set the default return value)
d ={'hello':'world'}print(d.get('hello','default_value')) # prints 'world'print(d.get('thingy','default_value')) # prints 'default_value'
The following code will filter the elements in the list according to conditions
a =[3,4,5]
b =[]for i in a:if i >4:
b.append(i)
In fact, you can use list comprehension or higher-order function filter to achieve
a =[3,4,5]
b =[i for i in a if i >4]
# Or:
b =filter(lambda x: x >4, a)
In addition to filter, two functions of map and reduce are also very useful
a =[3,4,5]
b =map(lambda i: i +3, a)
# b:[6,7,8]
File reading is a very common operation, after using the handle, you need to manually call the close function to close the handle
fp =open('file.txt')print(fp.read())
fp.close()
If the code is too long, even if you know you need to manually close the handle, you will often miss it. Therefore, it is recommended to develop a habit of using with open
to read and write files, the context manager will automatically perform the operation of closing the handle
withopen('file.txt')as fp:for line in fp.readlines():print(line)
Putting a long string in one line greatly affects the readability of the code (the code below can slide to the left)
long_string ='For a long time I used to go to bed early. Sometimes, when I had put out my candle, my eyes would close so quickly that I had not even time to say “I’m going to sleep.”'
People who pay attention to code readability will use three quotation marks \
to continue writing
long_string ='For a long time I used to go to bed early. ' \
' Sometimes, when I had put out my candle, ' \
' my eyes would close so quickly that I had not even time to say “I’m going to sleep.”'
However, for me, I prefer to use parentheses to wrap ()
long_string =("For a long time I used to go to bed early. Sometimes, ""when I had put out my candle, my eyes would close so quickly ""that I had not even time to say “I’m going to sleep.”")
The same is true when guiding the package
from some.deep.module.inside.a.module import(
a_nice_function, another_nice_function, yet_another_nice_function)
Sometimes out of necessity, we will use some special magic to adapt the code to more uncertain scenes.
def make_complex(*args):
x, y = args
returndict(**locals())
But if not necessary, please don't do that. Unreasonably increasing the uncertainty of the code will make the original dynamic language write more dynamic code.
def make_complex(x, y):return{'x': x,'y': y}
For variables that are not needed but have to be received, please use placeholders
filename ='foobar.txt'
basename, _, ext = filename.rpartition('.')
For the following writing
score =85if score >80 and score <90:print("good")
There is actually a better way to write
score =85if80< score <90:print("good")
If you understand the chain comparison operation above, then you should know why the output of the following line of code is False
>>> False == False == True
False
For simple judgment and assignment
age =20if age >18:
type ="adult"else:
type ="teenager"
In fact, you can use the trinocular calculation to do it in one line.
age =20
b ="adult"if age >18else"teenager"
Recommended Posts