Python表达式进阶——列表表达式

x = 0
y = x*2 if x >= 0 else x
print(y)

# [表达式for变量in列表]
l1 = []
l2 = [i for i in range(100) if i % 2 == 0]
print(l2)
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
b = [x**3 for x in a if x % 2 == 0 and x > 5]
print(b)

# 与zip结合
a = [1, 2, 3, 4, 5]
b = [6, 7, 8, 9, 10]
xy = [[x, y] for(x, y) in zip(a, b)]
print(xy)

# map
def f(x):
    return x**2
lis = [2, 3, 4, 5, 6]
lis1 = map(f, lis)
print(list(lis1))

# 获取两个列表对应位置上的最小值
l1 = [1, 2, 3, 4]
l2 = [4, 1, 6, 2]
mins = map(min, l1, l2)
print(*mins)
tup = (3, 4, 6)
print(*tup)
# print里面加*好打印的是什么类型?
# print(type(*tup))


# 数据清洗
def format_name(s):
    return s[0].upper() + s[1:].lower()

name = ["Tom", "jeery", "marry"]
nameList = map(format_name, name)
print(*nameList)


# 匿名函数lambda
# <函数名> = lambda<参数列表>:<表达式>
def f1(x, y):
    return x + y
# f1 = lambda x, y: x + y
# 如果使用VScode中的格式化保存的话,lambal表达式会自动转换成下面的格式
# def f(x, y): return x + y


# 多元赋值
x = 1
y = 3
x, y = y, x
print((x, y))

  

posted @ 2020-10-22 09:36  Veritas_des_Liberty  阅读(362)  评论(0编辑  收藏  举报