列表推导式、海象运算符

字典代替 switch

day = 8

def get_sunday():
    return 'Sunday'

def get_monday():
    return 'Monday'

def get_tuesday():
    return 'Tuesday'

def get_default():
    return 'Unkown'

switcher = {
    0: get_sunday,
    1: get_monday,
    2: get_tuesday
}

day_name = switcher.get(day, get_default)()
print(day_name)

列表推导式

根据一个列表创建一个新的列表

以 a 列表的每个元素的平方创建一个新列表

a = [1, 2, 3, 4, 5, 6]
b = [i*i for i in a]
print(b)

结果

[1, 4, 9, 16, 25, 36]

只用大于 3 的元素

a = [1, 2, 3, 4, 5, 6]
b = [i*i for i in a if i > 3]
print(b)

结果

[16, 25, 36]

tuple set dict 同样可以,比如 set

a = {1, 2, 3, 4, 5, 6}
b = {i*i for i in a if i > 3}
print(b)

结果

{16, 25, 36}

用字典的 key 创建一个新列表

students = {'张三': 18, '小明': 19, '小黑': 20}

l = [key for key,value in students.items()]
print(l)

结果

['张三', '小明', '小黑']

互换字典的 key 和 value

students = {'张三': 18, '小明': 19, '小黑': 20}

d = {value:key for key,value in students.items()}
print(d)

结果

{18: '张三', 19: '小明', 20: '小黑'}

iterator 和 generator

可迭代对象:凡是可以被 for 循环遍历的数据结构,都是可迭代对象。列表,元组等都是可迭代对象。

迭代器:迭代器一定是一个可迭代对象,可迭代对象不一定是迭代器。列表,元组等都不是迭代器。

普通对象拥有 __iter____next__ 两个方法,可以变成一个迭代器

定义一个迭代器

import re


class BookCollection:
    def __init__(self):
        self.data = ['《入门》', '《出门》', '《放弃》']
        self.cur = 0
    
    def __iter__(self):
        return self
    
    def __next__(self):
        if self.cur >= len(self.data):
            raise StopIteration()
        next_book = self.data[self.cur]
        self.cur += 1
        return next_book

books = BookCollection()
for book in books:
    print(book)

结果

《入门》
《出门》
《放弃》

迭代器有一次性,上面遍历过了,再次遍历不会打印

...
books = BookCollection()
for book in books:
    print(book)
# 再次遍历
for book in books:
    print(book)

结果,只有第一次遍历,打印了

《入门》
《出门》
《放弃》

如果要再次遍历,可以创建一个新的对象或者复制一个对象

...
books = BookCollection()
# 创建一个新的对象
books1 = BookCollection()

for book in books:
    print(book)

for book in books1:
    print(book)
...
books = BookCollection()
# 复制一个对象
import copy
books_copy = copy.copy(books)

for book in books:
    print(book)

for book in books_copy:
    print(book)

生成器

在函数中,执行 return ,函数就结束了。

yield 会返回一个生成器对象,生成器对象可以通过 next() 访问,也可以遍历

返回生成器对象之后,与 return 不同,下一次调用会接着从上一次返回的地方执行。

def gen(max):
    n = 0
    while n <= max:
        n += 1
        yield n

g = gen(10)
print(next(g))
print(next(g))
print(next(g))

结果

1
2
3

遍历

...
g = gen(10)
for i in g:
    print(i)

结果

1
2
3
4
5
6
...

dataclass

之前没有使用 dataclass

class Student:
    def __init__(self, name, age, school_name):
        self.name = name
        self.age = age
        self.school_name = school_name
    
    def test(self):
        print(self.name)

student = Student('张三', 18, 'python')
student.test()

使用 dataclass

from dataclasses import dataclass


@dataclass
class Student:
    name: str
    age: int
    school_name: str
    
    def test(self):
        print(self.name)

student = Student('张三', 18, 'python')
student.test()

海象运算符

使用前

a = 'python'

if len(a) > 5:
    print('长度为:' + str(len(a)))

使用后

a = 'python'

if (b:=len(a)) > 5:
    print('长度为:' + str(b))

另,使用 f 关键字做字符串拼接

a = 'python'

if (b:=len(a)) > 5:
    print(f'长度为:{b}')

你可能感兴趣的:(列表推导式、海象运算符)