1. 程式人生 > >Python列表推導式的使用和一些遍歷技巧

Python列表推導式的使用和一些遍歷技巧

參考連結

# -*-coding:utf8-*-

# 用列表推導式求矩陣的轉置
a = [[1, 2, 3, 4],
     [5, 6, 7, 8],
     [9, 10, 11, 12]]


def T(a):
    if len(a) == 0:  #空矩陣
        return []
    l = len(a[0])
    for i in range(1, len(a)):  #是不是一個矩陣
        if l != len(a[i]):
            return []
    return [[a[j][i] for j in range(len(a))] for i in range(len(a[0]))]


print(T(a))

# 用列表推導打贏乘法表
str1 = [str(j) + '*' + str(i) + '=' + str(i * j).center(2) + ' ' + ('\n' if i == j else '')
       for i in range(1, 10) for j in range(1, i + 1)]
print(''.join(str1))


# 用列表推導式構字典
print({i : i**3 for i in range(1, 11) if i % 2 == 1})

list1 = ['zhang', 'er', 'gou']
for ind, content in enumerate(list1):
    print(ind, content)

feature = [[1, 1], [1, -1], [1, 2], [-1, 1], [-1, -2]]
label = [1, 4, 1, 2, 3]
list2 = [1,2,3, 4, 5]
# zip(feature, label, list3)  # 可以打包更多
# 用zip打包列表
for point, local in zip(feature, label):
    print('座標({:d}, {:d})在第{:d}象限'.format(point[0], point[1], local))

# 反向迭代
print([it for it in reversed(list2)])