Python 是一种代表简单思想的语言,其语法相对简单,很容易上手。不过,如果就此小视 Python 语法的精妙和深邃,那就大错特错了。本文精心筛选了最能展现 Python 语法之精妙的十个知识点,并附上详细的实例代码。如能在实战中融会贯通、灵活使用,必将使代码更为精炼、高效,同时也会极大提升代码B格,使之看上去更老练,读起来更优雅。
for-else
>>> for i in [1,2,3,4]:
print(i)
else:
print(i, '我是else')
1
2
3
4
4 我是else
>>> for i in [1,2,3,4]:
if i > 2:
print(i)
else:
print(i, '我是else')
3
4
4 我是else
>>> for i in [1,2,3,4]:
if i>2:
print(i)
break
else:
print(i, '我是else')
3
一颗星()和两颗星(*)
>>> def multi_sum(*args):
s = 0
for item in args:
s += item
return s
>>> multi_sum(3,4,5)
12
>>> def do_something(name, age, gender='男', *args, **kwds):
print('姓名:%s,年龄:%d,性别:%s'%(name, age, gender))
print(args)
print(kwds)
>>> do_something('xufive', 50, '男', 175, 75, math=99, english=90)
姓名:xufive,年龄:50,性别:男
(175, 75)
{'math': 99, 'english': 90}
三元表达式
>>> y = 5
>>> if y < 0:
print('y是一个负数')
else:
print('y是一个非负数')
y是一个非负数
打球去吧 if 不下雨 else 去自习室
>>> y = 5
>>> print('y是一个负数' if y < 0 else 'y是一个非负数')
y是一个非负数
>>> y = 5
>>> x = -1 if y < 0 else 1
>>> x
1
with-as
fp = open(r'D:CSDNColumn empmpmap.py', 'r')
try:
contents = fp.readlines()
finally:
fp.close()
>>> with open(r'D:CSDNColumn empmpmap.py', 'r') as fp:
contents = fp.readlines()
列表推导式
在各种稀奇古怪的语法中,列表推导式的使用频率应该时最高的,对于代码的简化效果也非常明显。比如,求列表各元素的平方,通常应该这样写(当然也有其他写法,比如使用map函数):
>>> a = [1, 2, 3, 4, 5]
>>> result = list()
>>> for i in a:
result.append(i*i)
>>> result
[1, 4, 9, 16, 25]
>>> a = [1, 2, 3, 4, 5]
>>> result = [i*i for i in a]
>>> result
[1, 4, 9, 16, 25]
作者 | 许向武;责编 | 郭芮;出品 | CSDN 博客





































苏公安网备 32011402010933号