pythonic 代码_15个Pythonic的代码示例(值得收藏)

围观人数:

15

标签:module   lex   value   变量   filter   表达式   mod   pythonic   iso

01. 变量交换

Bad

tmp =a a=b b= tmp

Pythonic

a,b = b,a

02. 列表推导

Bad

my_list =[]for i in range(10): my_list.append(i*2)

Pythonic

my_list = [i*2 for i in range(10)]

03. 单行表达式

虽然列表推导式由于其简洁性及表达性,被广受推崇。

但是有许多可以写成单行的表达式,并不是好的做法。

Bad

print ‘one‘; print ‘two‘ if x == 1: print ‘one‘ if and :#do something

04. 带索引遍历

Bad

for i inrange(len(my_list)):print(i, "-->", my_list[i])

Pythonic

for i,item inenumerate(my_list):print(i, "-->",item)

05. 序列解包

Pythonic

a, *rest = [1, 2, 3]#a = 1, rest = [2, 3] a,*middle, c = [1, 2, 3, 4]#a = 1, middle = [2, 3], c = 4

06. 字符串拼接

Bad

letters = [‘s‘, ‘p‘, ‘a‘, ‘m‘] s="" for let inletters: s+= let

Pythonic

letters = [‘s‘, ‘p‘, ‘a‘, ‘m‘] word= ‘‘.join(letters)

07. 真假判断

Bad

if attr ==True:print ‘True!‘ if attr ==None:print ‘attr is None!‘

Pythonic

ifattr:print ‘attr is truthy!‘ if notattr:print ‘attr is falsey!‘ if attr isNone:print ‘attr is None!‘

08. 访问字典元素

Bad

d = {‘hello‘: ‘world‘}if d.has_key(‘hello‘):print d[‘hello‘] #prints ‘world‘ else:print ‘default_value‘

Pythonic

d = {‘hello‘: ‘world‘}print d.get(‘hello‘, ‘default_value‘) #prints ‘world‘ print d.get(‘thingy‘, ‘default_value‘) #prints ‘default_value‘ #Or: if ‘hello‘ ind:print d[‘hello‘]

09. 操作列表

Bad

a = [3, 4, 5] b=[]for i ina:if i > 4: b.append(i)

Pythonic

a = [3, 4, 5] b= [i for i in a if i > 4]#Or: b = filter(lambda x: x > 4, a)

Bad

a = [3, 4, 5]for i inrange(len(a)): a[i]+= 3

Pythonic

a = [3, 4, 5] a= [i + 3 for i ina]#Or: a = map(lambda i: i + 3, a)

10. 文件读取

Bad

f = open(‘file.txt‘) a=f.read()printa f.close()

Pythonic

with open(‘file.txt‘) as f:for line inf:printline

11. 代码续行

Bad

my_very_big_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.”""" from some.deep.module.inside.a.module importa_nice_function, another_nice_function, yet_another_nice_function

Pythonic

my_very_big_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.”")from some.deep.module.inside.a.module import( a_nice_function, another_nice_function, yet_another_nice_function)

12. 显式代码

Bad

def make_complex(*args): x, y=argsreturn dict(**locals())

Pythonic

defmake_complex(x, y):return {‘x‘: x, ‘y‘: y}

13. 使用占位符

Pythonic

filename = ‘foobar.txt‘basename, _, ext= filename.rpartition(‘.‘)

14. 链式比较

Bad

if age > 18 and age < 60:print("young man")

Pythonic

if 18 < age < 60:print("young man")

理解了链式比较操作,那么你应该知道为什么下面这行代码输出的结果是 False

>>> False == False ==True False

15. 三目运算

Bad

if a > 2: b= 2 else: b= 1 #b = 2

Pythonic

a = 3b= 2 if a > 2 else 1 #b = 2

(福利推荐:腾讯云最新优惠活动来了:云产品限时1折,云服务器低至88元/年 ,点击这里立即抢购:9i0i.cn/qcloud,腾讯云海外服务器1折抢购,免ICP备案,免费换IP,点击这里立即抢购:9i0i.cn/qcloudhw)

15个Pythonic的代码示例(值得收藏)

标签:module   lex   value   变量   filter   表达式   mod   pythonic   iso

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值