簡體   English   中英

Python,用於中斷重復的for循環

[英]Python, for loop for to break repetition

假設我有重復的內容,但只有一個數字變化。 例如,如何在一個for循環中做到這一點?

如您在本示例中看到的(下降到pic13),它使用變量和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_pos0self.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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM