Python学习之推导式的用法(3)

Python推导式是一种独特的数据处理方式,可以从一个数据序列构建另一个新的数据序列的结构体,某种程度上类似于java的对数据的处理方式。

它支持多种数据结构的推导式:

从字典里查了下,推导式的英语说法是derived types,comprehension, 以为衍生结构。

列表推导式:list comprehension

字典推导式:dict comprehension

集合推导式:set comprehension

元组推导式:tuple comprehension

以下逐个用例子来看下这些推导式是怎么处理数据的。

1. 列表推导式

def derv_type():
    # 1.list
    names = ['bob', 'tom', 'alie', 'jerry', 'wendy', 'smith']
    new_names = [name.upper() for name in names if len(name) > 3]
    print(new_names)
    multiples = [i for i in range(30) if i % 3 == 0]
    print(multiples)

输出:['ALIE', 'JERRY', 'WENDY', 'SMITH']
[0, 3, 6, 9, 12, 15, 18, 21, 24, 27]

2. 字典推导式

# 2.dict
    dic_hobby = ['basketball', 'badminton', 'pingpong', 'swimming']
    new_hobby = {key: len(key) for key in dic_hobby}
    print(new_hobby)
    dict_data = {x: x ** 2 for x in (2, 4, 8)}
    print(dict_data)
    print(type(dict_data))

输出:{'basketball': 10, 'badminton': 9, 'pingpong': 8, 'swimming': 8}
{2: 4, 4: 16, 8: 64}
<class 'dict'>

3. 集合推导式

# 3. set
set_new = {i ** 2 for i in (1, 2, 3)}
print(set_new)
one = {x for x in 'abracadabra' if x not in 'abc'}
print(one)
print(type(one))

输出:{1, 4, 9}
{'d', 'r'}
<class 'set'>

4. 元组推导式

# 4. tuple comprehension returns one generator object rather than other data types
two = (x for x in range(1, 12))
t_two = tuple(two)
print(two)  # <generator object derv_type.<locals>.<genexpr> at 0x0000014E75EFE510>
print(type(two))  # <class 'generator'>
print(t_two(1))  # tuple type object is not callable

输出:<generator object derv_type.<locals>.<genexpr> at 0x00000224214DE510>
<class 'generator'>

元组数据类型比较特殊,它返回的是个生成器对象,即generator, 且元组类型是用圆括号括起来的,不像集合是用大括号括起来,字典用中括号,列表用中括号。

以上就是python推导式的用法,可以用在对数据进行二次处理、筛选。多多练习,因为知易行难。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值