读书笔记:<python一行流> -- 2基础技巧

        这本书基本就是通过列表推导式,匿名函数,高阶函数,海象运算符等等技巧让很多程序变成只有一行代码,是一个炫技的好技能,不过作者克里斯蒂娜.迈耶完全是从开发实践出发,编写简洁,高性能的一行流.

关于炫技,比如看到有大神写的条件判断的7种方式中的.

age = 18
print(('未成年','成年了')[age > 18])
print((age>18) and '成年了' or '未成年')
print((lambda:"未成年", lambda:"已成年")[age > 18]()) # 最讨厌定义了lambda之后又用()调用了
print({True: "已成年", False: "未成年"}[age > 18])
print(((age > 18) and ("已成年",) or ("未成年",))[0])

感觉条件判断除了一板一眼地写和三元运算符之外,其他都有点就有点炫过头了.

第二章,主要是介绍一些基本的技巧

1.列表解析式(列表推导式)

# 1使用列表解析找出最高收入者
# 本例使用普通方法和列表解析来筛选一个字典中年薪高于10万美元的员工
employees = {
    'Alice':100000,
    'Bob' : 99817,
    'Carlo':122908,
    'Frank':88123,
    'Eve':93121
}
top_earns=[]
for k,v in employees.items():
    if v >= 100000:
        top_earns.append(k)
print(top_earns)
# >>>['Alice', 'Carlo']
# 一行流:列表推导式
print([k for k,v in employees.items() if v >= 100000])

"""列表推导式:
    [表达式 + 上下文]
    上下文决定列表要选择哪些元素
        上下文由一个或者多个for循环构成
        还可以通过if条件来限制上下文的范围
    表达式定义了被添加到列表之前需要做什么操作
        表达式可以是上下文中定义的任何变量的函数
        表达式是一个恒等的表达式,不会对上下文传过来的变量做任何改动
"""
# 一些示例:
print(' '.join(x.lower() for x in 'I AM NOT SHOUTING'.split()))  # 生成器表达式
print([(x,y) for x in range(3) for y in range(3) ])
print([x**2 for x in range(1,10) if x&1 ])
print([x**2 if (x&1) else x**3 for x in range(1,10)])


# 2使用列表解析找出高信息价值的单词
# 数据
"""背景:
    一般来说少于三个字母的单词提供的信息量很少,如a,is,and,the等,
    在一段文本中剔除所有少于三个字母组成的单词\
"""

text = '''
Great software is supported by great people.
    Our user base is enthusiastic, dedicated to 
    encouraging use of the language, 
 and committed to being diverse and friendly  .
'''

res_list = [[x.strip() for x in line.split() if len(x)>3] \
            for line in text.replace(',',' ').replace('.',' ').split('\n') if line]
print(res_list)

# 它是怎么工作的:这个一行流由两个嵌套的列表推导式构成,其结果是一个嵌套的列表
#     内层的[x.strip() for x in line.split() if len(x)>3]把一行文本中超过三个字母的单词加入列表
#     外层的for line in text.replace(',',' ').split('\n') if line]用于产生line,并过滤掉空行,去掉标点

# 文件读取-本文件
print([line.strip() for line in open('01列表解析.py','r',encoding='utf-8').read()])

2.lambda和map函数

# lambda函数
#     匿名函数,一般形式 lambda <参数列表>:返回值表达式
#     必定有返回值
#     lambda x : x+2
# map函数:映射函数
#   map(func,iterable):对于序列iterable中的每一个元素,执行func函数返回一个map对象,可以用list(map())转为列表


# 查看单词"is"是否在text的元素里面,如果在返回(True,item),不在返回(False,item)
text = [
    'Great software is supported by great people',
    'Our user base is enthusiastic, dedicated to ',
    'encouraging use of the language',
    'and committed to being diverse and friendly']
res = map(lambda x:(True,x) if 'is' in x else (False,x),text)
print(list(res))

# 使用列表推导
print([(True,x) if 'is' in x else (False,x) for x in text])


3.切片

# 切片的简单示例
s = 'Python’s standard documentation download, browse or watch a tutorial'

# print(s[:3])
# print(s[:])
# print(s[23:])
# print(s[3::2])
# print(s[3::-2])
# print(s[:8:-2])
# print(s[::4])
# print(s[:100])
# print(s[::-1])
# print(s[3:-2])

# 背景:
# 在一个多行字符串中找到一个搜索关键字,需要找到关键字的位置,并返回它所处的上下文环境,前后18个字符

text="""str(object='') -> str
    str(bytes_or_buffer[, encoding[, errors]]) -> str
    Create a new string object from the given object. If encoding or
    errors is specified, then the object must expose a data buffer
    that will be decoded using the given encoding and error handler.
    Otherwise, returns the result of object.__str__() (if defined)
    or repr(object).
    encoding defaults to sys.getdefaultencoding().
    errors defaults to 'strict'.
    """
# 一行流:
# find = lambda x,q:x[x.find(q)-18: x.find(q)+18] if q in x else -1
# 为了避免两次计算x.find(q)使用海象运算符:=保存中间结果index
find = lambda x,q:x[(index:=x.find(q))-18:index+18] if q in x else -1
print(find(text,'decoded'))
# 没有结果,原因是object首次出现的位置是4,即print(text[-14:22])所以结果为空
print(text[(i:=text.find('object'))-18:i+18])


# 切片赋值 把奇数项的值用前一项的值赋值
nums = ['111','000','222','000','333'
        ,'000','444','000','555','000']
nums[1::2] = nums[::2]
print(nums)


4.使用生成器表达式


# 求字典中至少给一个员工的工资低于最低工资标准150
companies = {
    'Coolcompany':{'员工1':200,'员工2':180,'员工3':115},
    'cheapcompany':{'员工3':300,'员工4':160,'员工5':245},
    'Sosocompany':{'员工7':99,'员工8':234,'员工9':100}
}
res = [x for x in companies if any(y < 150 for y in companies[x].values())]
print(res)

5.zip函数

a_list = [1,2,3]
b_list = [4,5,6]
zip_list = list(zip(a_list,b_list))
print(zip_list)
a,b = zip(*zip_list)  # 两次zip之后数据又回来了
print(a,b)

# 假设有一个列表,里面存储的是员工数据('姓名',工资,'职位'),如何把字段名称添加到员工数据中
datas = [('张三',10000,'清洁工'),
         ('李四',20000,'修电脑的'),
         ('王二麻子',100000,'老板')]
column_names = ['姓名','工资','职位']

db = [dict(zip(column_names,x)) for x in datas]
print(db)

生命不息,吃饭不止!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值