禅道——Pythonic

Python由其语言简洁性,使得写出优雅、地道和整洁的代码成为的一种禅道,最近工作中感触尤甚,特地回顾了基础知识,这里总结几种Pythonic的写法,自己备用。

定期整理点滴,完善自己,今后给我洋哥挣大钱,带她过好生活,陪伴着让我的小宝贝发自内心爱上笑,加油吧
数票子

python.txt:
hello, python

1、变量交换
a = 0
b = 1
a, b = b, a
print('a =', a, '\nb =', b)
2、列表推导
my_list = [i * 2 for i in range(10)]
print(my_list)
3、带索引遍历
for i, item in enumerate(my_list):
    print(i, '-->', item)
4、序列解包
a, *rest = [1, 2, 3]
print('a =', a, 'rest =', rest)
a, *middle, c = [1, 2, 3, 4]
print('a =', a, 'middle =', middle, 'c =', c)
5、字符串拼接
letters = ['s', 'p', 'a', 'm']
print(''.join(letters))
6、真假判断
a = 1
if a:
    print('a is True')

if not a:
    print('a is False')

a = None
if a is None:
   print('a is None')
7、访问字典元素
d = {'hello':'python'}
print(d.get('hello','default_value'))
print(d.get('things','default_value'))

> Or

if 'hello' in d:
    print dict['hello']
8、操作列表
a = [3, 4, 5]
b = [i for i a if i > 4]
> Or
b = list(filter(lambda x: x > 4, a))
print(b)

a = [i + 3 for i in a]
> Or
a = list(map(lambda x: x + 3, a))
print(a)
9、文件读取
with open('python.txt') as f:
    for line in f:
        print(line)
10、代码续行
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.”"
)
11、显式
def make_complex(x, y):
    return {'x': x, 'y': y}
12、用占位符
filename = 'python.txt'
basename, _, ext = filename.rpartition('.')
*链操作
if 18 < age < 60:
    print('young man')
print(True == False == True)
*三目运算
a = 3
b = 2 if a > 2 else 1
print(b)

a = 3, b = 1
print(a if a >= b else b)

def find_max(a, b, c):
    return a if a > b and a > c else (b if b > a and b > c else c)

计划写一系列完整的文章巩固所学,日后会做目录进行整理。
2018年9月11日17时于广州逸夫科学馆

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值