語法: 1.[expression for iter_val in iterable]2.[expression for iter_val in iterable if cond_expr]
l = [i**2 for i in range(1,11)]
print(l) # [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
#列出1-10中大於或等於4的數字的平方
l = [i**2 for i in range(1,11) if i>=4] # 判斷語句在內迴圈裡面
print(l) #[16, 25, 36, 49, 64, 81, 100]
#實現2個列表的元素逐一配合
l1 = ['x','y','z']
l2 = [1,2,3]
l3 = [(a,b) for a in l1 for b in l2] # l1 為大迴圈,
print(l3)
#[('x', 1), ('x', 2), ('x', 3), ('y', 1), ('y', 2), ('y', 3), ('z', 1), ('z', 2), ('z', 3)]
tuples_demo = [(1,2,3),(4,5,6),(7,8,9)]
flattened = [x for tup in tuples_demo for x in tup]
print(flattened) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
#等同於:
flattened =
for tup in tuples_demo:
for x in tup:
print(flattened) # [1, 2, 3, 4, 5, 6, 7, 8, 9] 與列表解析的順序是一樣的
#統計字串
words = 'i like pyhton do you'
print(sum([len(i) for i in words.split()])) # 去除空格, 16
#字典 使鍵和值交換
dt =
print() # key 必須寫在前面
print() #
python列表解析
列表解析是乙個列表對映出另乙個列表,它的基本形式是乙個方括號裡面包含乙個for語句對乙個iterable物件迭代 expression for target1 in iterable1 if condition1 for targetn in iterablen if conditionn 上面是列...
python 列表解析
m 1,2,3 4,5,6 7,8,9 col2 row 1 for row in m 獲取列表m的每個元素的第二個元素的值組成的列表 print col2 print row 1 1 for row in m 獲取列表m的每個元素的第二個元素 1的值組成的列表 print row 1 for ro...
python 列表解析
列表解析 list comprehensions 表示式 expression for iter val in iterable if cond expr print x,y for x in 1 2 for y in 3 4 print x,y for x in 1 2 for y in 3 x ...