赞
踩
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推导式的用法,可以用在对数据进行二次处理、筛选。多多练习,因为知易行难。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。