Python 列表推导式、生成器表达式、字典推导式、集合推导式的使用

Python 列表推导式、生成器表达式、字典推导式、集合推导式的使用

推导式是可以从一个数据序列构建另一个新的数据序列的结构体

一、列表推导式:

使用[]括号生成列表

常规操作:

# 需求:将my_list列表中的奇数取出, 并且将取出的奇数相乘, 并且返回
my_list = [1, 2, 3, 4, 5, 6, 7, 8]
new_list = []
for item in my_list:
    if item % 2 == 1:
        new_list.append(item*item)
print(new_list)

# 输出结果如下:[1, 9, 25, 49]

使用列表推导式操作:

my_list = [1, 2, 3, 4, 5, 6, 7, 8]
new_list = [item * item for item in my_list if item % 2 == 1]
print(new_list)

# 输出结果:[1, 9, 25, 49]

二、生成器表达式:

使用()括号变成生成器,将列表推导式[]改成()就可以得到生成器

my_list = [1, 2, 3, 4, 5, 6, 7, 8]
new_genertor = (item for item in my_list if item % 2 == 1)

print(new_genertor)  # 输出结果:<generator object <genexpr> at 0x0000027752962200>

# 循环生成器
for item in new_genertor:
    print(item)
# 输出结果如下:
1
3
5
7

三、字典推导式:

使用{}括号并且列表存放的是键值对,它就是字典推导式

my_dict = {"name": "fe_cow", "age": 22, "sex": "男"}
new_dict = {value: key for key, value in my_dict.items()}

print(type(new_dict))
# 输出结果:<class 'dict'>  可以看出是一个字典

print(new_dict)
# 输出结果:{'fe_cow': 'name', '男': 'sex', 22: 'age'}   仅是将字典中的键值掉换了位置

四、集合推导式:

集合推导式使用的同样是{}括号来表示,唯一跟字典推导式不同的是,它里面不是键值对

my_dict = {"name": "fe_cow", "age": 22, "sex": "男"}
new_set = {key for key, value in my_dict.items()}

print(type(new_set))
# 输出结果:<class 'set'>   可以看出它是一个集合类型

print(new_set)
# 输出结果:{'sex', 'name', 'age'}

以上都是一些推导式的简单使用,不建议较复杂的逻辑使用推导式来进行处理,因为代码的可读性是很重要的

猜你喜欢

转载自blog.csdn.net/Fe_cow/article/details/95061455
今日推荐