您可以使用enumerate()
來計算你的迭代:
animations = {
action : {
direction : (
(duration, (i * len(directions) + j, x)) for x in frames
) for j, direction in enumerate(directions)
} for i, action in enumerate(actions)
}
這將產生:
>>> pprint({action: {direction: [(duration, (i * len(directions) + j, x)) for x in frames] for j, direction in enumerate(directions) } for i, action in enumerate(actions)})
{'death': {'down': [(0.2, (12, 0)),
(0.2, (12, 1)),
(0.2, (12, 2)),
(0.2, (12, 3))],
'left': [(0.2, (14, 0)),
(0.2, (14, 1)),
(0.2, (14, 2)),
(0.2, (14, 3))],
'right': [(0.2, (15, 0)),
(0.2, (15, 1)),
(0.2, (15, 2)),
(0.2, (15, 3))],
'up': [(0.2, (13, 0)),
(0.2, (13, 1)),
(0.2, (13, 2)),
(0.2, (13, 3))]},
'fight': {'down': [(0.2, (8, 0)),
(0.2, (8, 1)),
(0.2, (8, 2)),
(0.2, (8, 3))],
'left': [(0.2, (10, 0)),
(0.2, (10, 1)),
(0.2, (10, 2)),
(0.2, (10, 3))],
'right': [(0.2, (11, 0)),
(0.2, (11, 1)),
(0.2, (11, 2)),
(0.2, (11, 3))],
'up': [(0.2, (9, 0)), (0.2, (9, 1)), (0.2, (9, 2)), (0.2, (9, 3))]},
'idle': {'down': [(0.2, (0, 0)),
(0.2, (0, 1)),
(0.2, (0, 2)),
(0.2, (0, 3))],
'left': [(0.2, (2, 0)),
(0.2, (2, 1)),
(0.2, (2, 2)),
(0.2, (2, 3))],
'right': [(0.2, (3, 0)),
(0.2, (3, 1)),
(0.2, (3, 2)),
(0.2, (3, 3))],
'up': [(0.2, (1, 0)), (0.2, (1, 1)), (0.2, (1, 2)), (0.2, (1, 3))]},
'walk': {'down': [(0.2, (4, 0)),
(0.2, (4, 1)),
(0.2, (4, 2)),
(0.2, (4, 3))],
'left': [(0.2, (6, 0)),
(0.2, (6, 1)),
(0.2, (6, 2)),
(0.2, (6, 3))],
'right': [(0.2, (7, 0)),
(0.2, (7, 1)),
(0.2, (7, 2)),
(0.2, (7, 3))],
'up': [(0.2, (5, 0)), (0.2, (5, 1)), (0.2, (5, 2)), (0.2, (5, 3))]}}
或者,使用itertools.count()
object與next()
;如果內部循環使用基於外部循環的可變數量的元素,這很有幫助:
from itertools import count
iter_count = count()
animations = {
action : {
direction : (
(duration, (count, x)) for c in (next(iter_count),) for x in frames
) for direction in directions
} for action in actions
}
您是否嘗試過使用'range'?嘗試'爲我在範圍內(len(方向))'? – nish
通過'actions','directions'或'frames'獲取迭代編號?或所有3的產品? –
@MartijnPieters的方向+行動 –