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

你可能感兴趣的:(Python,python,机器学习)