zip(*iterables, strict=False)
*iterables:
可迭代物件
strict:
當設定為True,若可迭代物件長度不一致時,會產生異常
1 2 3 4 5 6 7 8 |
x = ['a', 'b', 'c'] y = [1, 2, 3] print(list(zip(x, y))) # [('a', 1), ('b', 2), ('c', 3)] z = [4, 5, 6, 7] print(list(zip(x, z, strict=True))) # ValueError: zip() argument 2 is longer than argument 1 |
使用zip搭配for loop,可非常簡潔地產生座標給PyQt QGridLayout使用
positions list中的元素為 tuple,zip產生的position也是tuple
拆解:
positions list: [(0, 0), (0, 1), …, (4, 3)]
list(zip(positions, name)): [((0, 0), ‘Cls’), ((0, 1), ‘Black’), …, ((4, 3), ‘+’)]
position: (0, 0), …, (4, 3)
name: Cls, Back, …, +
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
# -*- coding: utf-8 -*- import sys from PyQt5.QtWidgets import QApplication, QWidget, QGridLayout, QPushButton class Winform(QWidget): def __init__(self, parent=None): super(Winform, self).__init__(parent) self.initUI() def initUI(self): grid = QGridLayout() self.setLayout(grid) names = ['Cls', 'Back', '', 'Close', '7', '8', '9', '/', '4', '5', '6', '*', '1', '2', '3', '-', '0', '.', '=', '+'] positions = [(i, j) for i in range(5) for j in range(4)] for position, name in zip(positions, names): if name == '': continue button = QPushButton(name) # addWidget(QWidget widget, int row, int col, int alignment=0) # position: (0, 0) ~ (4, 3) # *position: 0 0 ~ 4 3 grid.addWidget(button, *position) self.move(300, 150) self.setWindowTitle('網格佈局') if __name__ == "__main__": app = QApplication(sys.argv) form = Winform() form.show() sys.exit(app.exec_()) |