Python, for 循环 for 打破重复
Python, for loop for to break repetition
假设我有重复但只有一个数字改变的东西。例如,我怎样才能在一个 for 循环中做到这一点?
正如您在这个例子中看到的(下图 13),它使用变量和 qt 名称,如 self.hand_pos1
。
pic0 = os.path.join(path, 'tiles', '%s.png' % player_hand[0])
self.hand_pos0.setPixmap(QtGui.QPixmap(pic0))
pic1 = os.path.join(path, 'tiles', '%s.png' % player_hand[1])
self.hand_pos1.setPixmap(QtGui.QPixmap(pic1))
pic2 = os.path.join(path, 'tiles', '%s.png' % player_hand[2])
self.hand_pos2.setPixmap(QtGui.QPixmap(pic2))
pic3 = os.path.join(path, 'tiles', '%s.png' % player_hand[3])
self.hand_pos3.setPixmap(QtGui.QPixmap(pic3))
pic4 = os.path.join(path, 'tiles', '%s.png' % player_hand[4])
self.hand_pos4.setPixmap(QtGui.QPixmap(pic4))
pic5 = os.path.join(path, 'tiles', '%s.png' % player_hand[5])
self.hand_pos5.setPixmap(QtGui.QPixmap(pic5))
您可以迭代,然后访问数组的元素。要访问具有动态名称的属性,您可以使用 getattr
.
for elem in range(14):
pic = os.path.join(path, 'tiles', '{}.png'.format(player_hand[elem]))
getattr(self, "hand_pos{}".format(elem)).setPixmap(QtGui.QPixmap(pic))
但考虑用列表或字典替换 self.hand_posX
属性。
而不是让 self.hand_pos0
、self.hand_pos1
等将它们全部收集到一个列表中。然后你可以这样做:
for position, hand in zip(self.hand_pos, player_hand):
pic = os.path.join(path, 'tiles', '%s.png', % hand)
position.setPixMap(QtGui.QPixmap(pic)
假设我有重复但只有一个数字改变的东西。例如,我怎样才能在一个 for 循环中做到这一点?
正如您在这个例子中看到的(下图 13),它使用变量和 qt 名称,如 self.hand_pos1
。
pic0 = os.path.join(path, 'tiles', '%s.png' % player_hand[0])
self.hand_pos0.setPixmap(QtGui.QPixmap(pic0))
pic1 = os.path.join(path, 'tiles', '%s.png' % player_hand[1])
self.hand_pos1.setPixmap(QtGui.QPixmap(pic1))
pic2 = os.path.join(path, 'tiles', '%s.png' % player_hand[2])
self.hand_pos2.setPixmap(QtGui.QPixmap(pic2))
pic3 = os.path.join(path, 'tiles', '%s.png' % player_hand[3])
self.hand_pos3.setPixmap(QtGui.QPixmap(pic3))
pic4 = os.path.join(path, 'tiles', '%s.png' % player_hand[4])
self.hand_pos4.setPixmap(QtGui.QPixmap(pic4))
pic5 = os.path.join(path, 'tiles', '%s.png' % player_hand[5])
self.hand_pos5.setPixmap(QtGui.QPixmap(pic5))
您可以迭代,然后访问数组的元素。要访问具有动态名称的属性,您可以使用 getattr
.
for elem in range(14):
pic = os.path.join(path, 'tiles', '{}.png'.format(player_hand[elem]))
getattr(self, "hand_pos{}".format(elem)).setPixmap(QtGui.QPixmap(pic))
但考虑用列表或字典替换 self.hand_posX
属性。
而不是让 self.hand_pos0
、self.hand_pos1
等将它们全部收集到一个列表中。然后你可以这样做:
for position, hand in zip(self.hand_pos, player_hand):
pic = os.path.join(path, 'tiles', '%s.png', % hand)
position.setPixMap(QtGui.QPixmap(pic)