10个技巧让你的代码更优雅

阅读本文需要大约 2 分钟。
现在写代码的门槛非常低了,少儿都开始编程了,但从代码的风格一眼看出编码水平。是的,写代码是容易的,写出易读的代码也是容易的,但写出易读、优雅、高效的代码则需要经验的积累。今天分享 10 个技巧帮你写出更优雅、更符号 Pythonic 风格的代码。

1、三元表达式

通常情况下,条件表达式是这样写的:
 
   
condition =  True

if condition:
    x =  1
else:
    x =  0

print(x)
更易读,更优雅,代码量更少的做法是这样的:
 
   
condition =  True

x =  1  if condition  else  0

print(x)
这就是三元表达式。类似其他语言的问号表达式。

2、使用下划线分隔大数

 
   
num1 =  100000000
num2 =  10000000
total = num1 + num2 
print(total)
# 110000000
可以写成这样
 
   
num1 =  10_000_0000
num2 =  10_000_000
total = num1 + num2 
print(total)
# 110000000
如果想让输出结果中使用逗号分隔,还可以这样:
 
   
num1 =  10_000_0000
num2 =  10_000_000
total = num1 + num2 
print( f"{total:,}")
# 110,000,000
这样使大数看起来更容易让人类阅读。

3、使用上下文管理器with

通常打开一个文件操作如下所示:
 
   
f = open( "text.txt", "r")
file_contents = f.read()
f.close()

words = file_contents.split( " ")
word_count = len(words)
print(word_count)
更好的实践是使用上下文管理器 with,这样Python解释器会自动处理文件的关闭操作。这样的用法可以推广到更多IO操作的地方,省去关闭操作:
 
   
with open( "text.txt", "r"as f:
    file_contents = f.read()

words = file_contents.split( " ")
word_count = len(words)
print(word_count)

4、使用 enumerate

 
   
names = [ 'dvid', 'xiaoming', 'lilei', 'hanmeimei']

index =  0
for name  in names:
    print(index,name)
    index +=  1
获取列表的索引完全可以这样使用:
 
   
names = [ 'dvid', 'xiaoming', 'lilei', 'hanmeimei']


for index,name  in enumerate(names):
    print(index,name)

5、使用 zip

出现两个列表,需要一一映射时,通常,你可能会这样写:
 
   
names = [ '艾米莉亚·克拉克', '基特·哈灵顿', '麦茜·威廉姆斯', '彼特·丁拉基']
roles = [ '丹妮莉丝·坦格利安', '琼恩·雪诺', '艾莉亚·史塔克', '提利昂·兰尼斯特']

for index,name  in enumerate(names):
    print( f"{name} 扮演 {roles [index]}")
如果使用 zip,将变更更加简单:
 
   
names = [ '艾米莉亚·克拉克', '基特·哈灵顿', '麦茜·威廉姆斯', '彼特·丁拉基']
roles = [ '丹妮莉丝·坦格利安', '琼恩·雪诺', '艾莉亚·史塔克', '提利昂·兰尼斯特']

for name,role  in zip(names,roles):
    print( f"{name} 扮演 {role}")
输出结果均为
 
   
艾米莉亚·克拉克 扮演 丹妮莉丝·坦格利安
基特·哈灵顿 扮演 琼恩·雪诺
麦茜·威廉姆斯 扮演 艾莉亚·史塔克
彼特·丁拉基 扮演 提利昂·兰尼斯特
zip 支持多个可迭代对象,如:
 
   
>>> a=[ 'a', 'b', 'c']
>>> b=[ 1, 2, 3, 4, 5]
>>> c=[ 'A', 'B', 'C', 'D']
>>>
>>> list(zip(a,b,c)]
[( 'a'1'A'), ( 'b'2'B'), ( 'c'3'C')]
>>>
zip 自动按最短的列表来进行组合映射,比自己编码代码容错性要高得多。

6、开箱

一般的变量赋值:
 
   
a,b,c =  1, 2, 3
当变量更多时还可以这样灵活赋值:
 
   
>>> a,b,*c,d=( 1, 2, 3, 4, 5, 6)
>>> print( "a=",a, "b=",b, "c=",c, "d=",d)
a=  1 b=  2 c= [ 345] d=  6
这种方式叫就做开箱,命名非常形象。

7、输入密码时使用 getpass

获取用户输入时, input 会回显输入的字符,当输入的是密码时,将会暴露密码,因此输入密码时请使用 getpass 模块,不回显输入的字符,起到保护密码的作用:
 
   
>>> password = input( "请输入密码:")
请输入密码:mypassword
>>> password
'mypassword'
>>>  from getpass  import getpass
>>> password2 = getpass( "请输入密码:")
请输入密码:
>>> password2
'123456'
>>>

8、使用 map 函数

 
   
map(function, iterable, ...)
map() 会根据提供的函数对指定序列做映射。第一个参数 function 以参数序列中的每一个元素调用 function 函数,返回包含每次 function 函数返回值的新列表。使用方法:
 
   
>>> def square(x) :             # 计算平方数
...      return x **  2
... 
>>> map(square, [ 1, 2, 3, 4, 5])    # 计算列表各个元素的平方
[ 1491625]
>>> map( lambda x: x **  2, [ 12345])   # 使用 lambda 匿名函数
[ 1491625]

# 提供了两个列表,对相同位置的列表数据进行相加
>>> map( lambda x, y: x + y, [ 13579], [ 246810])
[ 37111519]

8、使用 reduce 函数

reduce() 函数会对参数序列中元素进行累积。函数将一个数据集合(链表,元组等)中的所有数据进行下列操作:用传给 reduce 中的函数 function(有两个参数)先对集合中的第 1、2 个元素进行操作,得到的结果再与第三个数据用 function 函数运算,最后得到一个结果。使用方法如下:
 
   
>>> def add(x, y) :             # 两数相加
...      return x + y
... 
>>> reduce(add, [ 1, 2, 3, 4, 5])    # 计算列表和:1+2+3+4+5
15
>>> reduce( lambda x, y: x+y, [ 1, 2, 3, 4, 5])   # 使用 lambda 匿名函数
15
语法
reduce() 函数语法:
reduce(function, iterable[, initializer])

10、使用 help dir 函数获取帮助

当没有网,没有手册时,如何获取一个模块的使用方法呢?我们可以直接进入 python 解释器环境,使用 help 和 dir 函数:
 
   
>>>  import smtpd
>>> help(smtpd)
Help on module smtpd:

NAME
    smtpd - An RFC  5321 smtp proxy  with optional RFC  1870  and RFC  6531 extension
s.

DESCRIPTION
    Usage: %(program)s [options] [localhost:localport [remotehost:remoteport]]

    Options:

        --nosetuid
        -n
            This program generally tries to setuid `nobody ', unless this flag is
            set.  The setuid call will fail if this program is not run as root (
in
            which case, use this flag).

        --version
        -V
            Print the version number and exit.

        --class classname
        -c classname

>>> from datetime import datetime
>>> dir(datetime)
['
__add__ ', '__class__ ', '__delattr__ ', '__dir__ ', '__doc__ ', '__eq__ ', '__forma
t__ ', '__ge__ ', '__getattribute__ ', '__gt__ ', '__hash__ ', '__init__ ', '__init_su
bclass__ ', '__le__ ', '__lt__ ', '__ne__ ', '__new__ ', '__radd__ ', '__reduce__ ', '_
_reduce_ex__ ', '__repr__ ', '__rsub__ ', '__setattr__ ', '__sizeof__ ', '__str__ ', '
__sub__ ', '__subclasshook__ ', 'astimezone ', 'combine ', 'ctime ', 'date ', 'day ', '
dst ', 'fold ', 'fromisoformat ', 'fromordinal ', 'fromtimestamp ', 'ho ur', 'isocalen
da r', 'isoformat ', 'isoweekday ', 'max ', 'microsecond ', 'min ', 'minute ', 'month ',
 '
now ', 'replace ', 'resolution ', 'second ', 'strftime ', 'strptime ', 'time ', 'time
stamp ', 'timetuple ', 'timetz ', 'today ', 'toordinal ', 'tzinfo ', 'tzname ', 'utcfro
mtimestamp ', 'utcnow ', 'utcoffset ', 'utctimetuple ', 'weekday ', 'yea r']
>>>
(完)
专注于Python技术分享
订阅、在看、转发是真情
640?wx_fmt=jpeg


发布了45 篇原创文章 · 获赞 44 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/somenzz/article/details/103083054