列表推倒式
Posted jnsn
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了列表推倒式相关的知识,希望对你有一定的参考价值。
列表推倒式
# 循环模式:[变量(加工的变量) for 变量 in iterable]
# 筛选模式: [变量(加工的变量) for 变量 in iterable if 条件]
# 多层嵌套
l = [x for x in range(1, 11, 2)]
print(l) # [1, 3, 5, 7, 9]
l = [x**2 for x in range(10)]
print(l) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# [‘python0期‘, ‘python1期‘, ‘python2期‘, ‘python3期‘, ‘python4期‘]
l = [f‘python{x}期‘ for x in range(5)]
print(l)
l = [i for i in range(30) if i % 3 ==0]
print(l) # [0, 3, 6, 9, 12, 15, 18, 21, 24, 27]
l = [‘hello‘, ‘hi‘, ‘wonderful‘]
l1 = [x.upper() for x in l if len(x) > 3]
print(l1) # [‘HELLO‘, ‘WONDERFUL‘]
# 多重循环
names = [[‘Tom‘, ‘Billy‘, ‘Jefferson‘, ‘Andrew‘, ‘Wesley‘, ‘Steven‘, ‘Joe‘],
[‘Alice‘, ‘Jill‘, ‘Ana‘, ‘Wendy‘, ‘Jennifer‘, ‘Sherry‘, ‘Eva‘]]
# 普通方式
l1 = []
for i in names:
for j in i:
if j.count(‘e‘) >= 2:
l1.append(j.upper())
print(l1)
# 列表推倒式方式
name = [j.upper() for x in names for j in x if j.count(‘e‘) >= 2]
print(name)
# 生成器表达式也包括循环模式。筛选模式, 嵌套等 。
# 列表推倒式[] 生成器表达式()
# 列表推倒式是 iterable ; 生成器表达式是iterator
l = (x for x in range(3))
print(type(l)) # <class ‘generator‘>
# print(next(l)) # 0
# print(next(l)) # 1
for i in l:
print(i) # 0 1 2
# 字典推倒式
name = [‘路飞‘, ‘娜美‘, ‘罗宾‘]
hobby = [‘肉‘, ‘钱‘, ‘考古‘]
# 方式1
dic = {}
for i in range(len(name)):
dic[name[i]] = hobby[i]
print(dic) # {‘路飞‘: ‘肉‘, ‘娜美‘: ‘钱‘, ‘罗宾‘: ‘考古‘}
# 方式2
dic = {name[i]: hobby[i] for i in range(len(name))}
print(dic) # {‘路飞‘: ‘肉‘, ‘娜美‘: ‘钱‘, ‘罗宾‘: ‘考古‘}
# 集合推倒式
print({x for x in range(3)}) # {0, 1, 2}
以上是关于列表推倒式的主要内容,如果未能解决你的问题,请参考以下文章