推導式試題

2022-06-30 11:21:10 字數 2767 閱讀 6285

#(1). 把字典寫成x=a,y=b,z=c的列表推導式

dic =

# for a,b in dic.items():

# print(a,b)

res = [a+"="+b for a,b in dic.items() ]

print(res)

# (2).把列表中所有字元變成小寫 ["addd","ddddd","ddaa","sss"]

lst = ["addd","ddddd","ddaa","sss"]

res = [i.lower() for i in lst ]

print(res)

# (3).x是0-5之間的偶數,y是0-5之間的奇數 把x,y組成一起變成元組,放到列表當中

# (0 2 4 )

# (1 3 5)

# (0 1) (0 3) (0 5)

# (2 1) (2 3) (2 5)

# (4 1) (4 3) (4 5)

lst_new =

for i in range(0,6):

if i % 2 == 0:

for j in range(0,6):

if j % 2 == 1:

print(lst_new)

# 寫法一

res = [(i,j) for i in range(0,6) if i % 2 == 0 for j in range(0,6) if j % 2 == 1 ]

print(res)

lst_new2 =

for i in range(0,6):

for j in range(0,6):

if i % 2==0 and j %2 ==1:

print(lst_new2)

# 寫法二

res = [(i,j) for i in range(0,6) for j in range(0,6) if i % 2 == 0 and j % 2 == 1 ]

print(res)

# (4).使用列表推導式 製作所有99乘法表中的運算

for i in range(1,10):

for j in range(1,i+1):

# print("%d*%d=%2d " % (i,j,i*j))

print(" * = ".format(i,j,i*j) ,end="")

print()

# 寫法一

res = [" * = ".format(i,j,i*j) for i in range(1,10) for j in range(1,i+1)]

print(res)

for i in range(9,0,-1):

for j in range(1,i+1):

# print("%d*%d=%2d " % (i,j,i*j))

print(" * = ".format(i,j,i*j) ,end="")

print()

# 寫法二

res = [" * = ".format(i,j,i*j) for i in range(9,0,-1) for j in range(1,i+1)]

print(res)

'''(5)#求m,n中矩陣和元素的乘積

# m = [ [1,2,3], 

#    [4,5,6], 

#    [7,8,9] ] 

# n = [ [2,2,2], 

#    [3,3,3], 

#    [4,4,4] ] 

=>實現效果1 [2, 4, 6, 12, 15, 18, 28, 32, 36]

=>實現效果2 [[2, 4, 6], [12, 15, 18], [28, 32, 36]]

'''m = [[1,2,3],[4,5,6],[7,8,9]]

n = [[2,2,2],[3,3,3],[4,4,4]]

# m[0][0] * n[0][0] = 2

# m[0][1] * n[0][1] = 4

# m[0][2] * n[0][2] = 6

# m[1][0] * n[1][0] = 12

# m[1][1] * n[1][1] = 15

# m[1][2] * n[1][2] = 18

# m[2][0] * n[2][0] = 28

# m[2][1] * n[2][1] = 32

# m[2][2] * n[2][2] = 36

# 效果1 # i=> 0 1 2 j=> 0 1 2 i動的慢 j動的塊

res = [m[i][j] * n[i][j] for i in range(3) for j in range(3) ]

print(res) #[2, 4, 6, 12, 15, 18, 28, 32, 36]

#=>實現效果2 [ [2, 4, 6], [12, 15, 18], [28, 32, 36] ]

#

'''第一步遍歷三個空列表

[ for i in range(3) ]

第二部在空列表裡面在寫乙個推導式遍歷對應的元素

[m[i][j] * n[i][j] for j in range(3)]

'''res = [ [m[i][j] * n[i][j] for j in range(3)] for i in range(3) ]

print(res) #[[2,4,6], , ]

Python列表推導式,集合推導式,元組推導式

先定義乙個列表a a 1,2,3,4,5,6,7,8 1a 1,2,3,4,5,6,7,8 列表推導 d i 2 for i in a 集合推導 e 元組推導 f i 2 for i in a print type d print type e print type f 輸出 123 4567 89...

python 推導 Python 推導式

python 語言有一種獨特的語法,它可以用最簡單的方式生成乙個列表 元組或字典,它們叫推導式。常見的推導式 列表推導式 字典推導式 集合推導式 列表推導式 列表推導式可以快速生成乙個列表,其語法格式為 x x for x in range 6 結果 0,1,4,9,16,25 相當於 l for ...

Python面試題之列表推導式

生成如下列表 0,0,0,0,0,0,1,2,3,4,0,2,4,6,8,0,3,6,9,12,考察列表生成式和基本邏輯推理 方法1 list1 forin range 4 temp for j in range 5 print list1 方法2 list1 i j for j in range ...