我有以下代码,并试图使其更短。我已经尝试过使用while和for循环,但是无法使其正常工作。我也在Stackoverflow上进行了搜索,发现了枚举和循环循环,但是不断出错或通常不知道我在做什么。有什么办法可以缩短这个时间?
我正在唱歌的pygame兼容版本和idlex的python 3.2。
players = [npc1,npc2,npc3,human] # these are classes
# sets new order of players after being mixed
first_player = players[0]
second_player = players[1]
third_player = players[2]
fourth_player = players[3]
# sets players prey...goes one ahead in the index, wrap around at end
first_players_prey = players[1]
second_players_prey = players[2]
third_players_prey = players[3]
fourth_players_prey = players[0]
# sets players predator, goes back one in the index, wrap around
first_players_predator = players[3]
second_players_predator = players[0]
third_players_predator = players[1]
fourth_players_predator = players[2]
# sets players grand prey/predator while only 4 players, goes 2 ahead/back in index, wrap around
first_players_grand_prey_predator = players[2]
second_players_grand_prey_predator = players[3]
third_players_grand_prey_predator = players[0]
fourth_players_grand_prey_predator = players[1]
尽管是非常规的,但是exec函数可用于完成您所追求的目标。(我还不太擅长Python,可能有更好的方法)我在编写的类中使用了类似的方法。名单可以容纳的值first
,虽然对fourth
,然后将不同角色的名称。然后可以使用它在几行中重新创建代码。
numbers = ['first', 'second', 'third', 'fourth']
roles = ['', '_prey', '_predator', '_grand_prey_predator']
values = [0, 1, 2, 3]
for i in range(4):
for j in range(4):
exec(numbers[j] + '_player' + roles[i] + ' = players[' + str(values[j]) + ']')
values = values[1:4] + values[:1]
我希望这回答了你的问题。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句