我可以使用循环缩短代码吗?

时间:2016-12-09 19:18:49

标签: python-3.x

我有以下代码,并试图缩短它。我尝试过使用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]

2 个答案:

答案 0 :(得分:0)

虽然非传统,但exec功能可以用来完成你所追求的目标。 (我对Python不太擅长,可能有更好的方法)我在我写过的类中使用了类似的方法。列表可以保存firstfourth的值,然后是不同角色的名称。这可以用来在几行中重新创建代码。

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]

我希望这能回答你的问题。

答案 1 :(得分:0)

您可以通过创建字典列表来缩短它。该列表包含玩家1在列表中排在第一位且玩家4排在最后位置的玩家。每个玩家被定义为一个字典,包括他们的阶级,猎物,大猎物和捕食者。

classes = ['npc1', 'npc2', 'npc3', 'human']  # These are classes
players = []
for i in range(4):
    players.append(
        {
            'class': classes[i],
            'prey': classes[(i + 1) % 4],
            'grand prey': classes[(i + 2) % 4],
            'predator': classes[(i + 3) % 4]
        }
    )

这可以进一步缩短为两行

classes = ['npc1', 'npc2', 'npc3', 'human']  # these are classes
players = [{'class': classes[i], 'prey': classes[(i + 1) % 4], 'grand prey': classes[(i + 2) % 4], 'predator': classes[(i + 3) % 4]} for i in range(4)]

但这可能是将它推向远方。最好让代码延伸到多行并且可读,反之亦然。