1. 程式人生 > >列表推導式和生成器表達式

列表推導式和生成器表達式

列表 title def yield 復制 upper set www. 代碼

列表推導式和生成器表達式

列表推導式#y = [1,2,3,4,5,6,7,8]轉化為x = [1,4,9,16,25,36,49,64]

技術分享圖片
x = []
for i in y:
    x.append(i*i)
print(x)
x = [i*i for i in y]
print(x)
#100以內數的一半 range(100) x2 = [i/2 for i in range(100)] print(x2)
技術分享圖片

生成器表達式:列表推導式的[]換成()就是生成器表達式

技術分享圖片
x = [i*i for i in y]
print(x)
g = (i*i for i in y)
print(g)
print(list(g))
for i in g:
    print(i)

列表推導式轉換生成器表達式
l = [‘雞蛋%s‘%i for i in range(10)]
print(l)
laomuji = (‘雞蛋%s‘%i for i in range(10))
for egg in laomuji:
    print(egg)
技術分享圖片

30以內能被三整除的數

技術分享圖片
#for循環
new_l = [] for i in range(30): if i%3 == 0: new_l.append(i) print(new_l) #列表切片 print(list(range(0,30,3)))
列表推導式 print([i for i in range(30) if i%3 == 0]) [i*i for i in range(30) if i%3 == 0]
技術分享圖片

平方補充square

def square(x):
    return x*x


[square(i) for i in range(30) if i%3 == 0]

找出列表中含有兩個或兩個以上“e”的元素

names = [[‘Tom‘, ‘Billy‘, ‘Jefferson‘, ‘Andrew‘, ‘Wesley‘, ‘Steven‘, ‘Joe‘],
         [‘Alice‘, ‘Jill‘, ‘Ana‘, ‘Wendy‘, ‘Jennifer‘, ‘Sherry‘, ‘Eva‘]]
ret = (name for name_lst in names for name in name_lst if name.count(‘e‘) >= 2)
print(ret)

字典表達式

#key,value互換
mcase = {‘a‘: 10, ‘b‘: 34} mcase_frequency = {mcase[k]:k for k in mcase} print(mcase_frequency)
#key合並同名為小寫,value相加
mcase = {‘a‘: 10, ‘b‘: 34, ‘A‘: 7, ‘Z‘: 3} mcase_frequency = {k.lower(): mcase.get(k.lower(), 0) + mcase.get(k.upper(), 0) for k in mcase} print(mcase_frequency)
#平方去重
squared = {x**2 for x in [1, -1, 2]} #{1,4} print(squared) # Output: set([1, 4])

生成器面試題

技術分享圖片
def demo():
    for i in range(4):
        yield i

g=demo()   # 生成器

g1=(i for i in g) #生成器
g2=(i for i in g1) #g2 生成器

print(list(g1))   #[0,1,2,3]
print(list(g2))  #[]
技術分享圖片 技術分享圖片
def add(n,i):
    return n+i

def tes():
    for i in range(4):
        yield i

g=tes()
for n in [1,5,10]:
    g=(add(n,i) for i in g)
# n=1
# g=(add(n,i) for i in tes())
# n = 5
# g=(add(n,i) for i in (add(n,i) for i in tes()))
# n = 10
# g=(add(n,i) for i in (add(n,i) for i in (add(n,i) for i in tes())))
print(list(g))  #[30, 31, 32, 33]
技術分享圖片

列表推導式和生成器表達式