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

我讨厌Python我爱Pygame

我有以下代码,并试图使其更短。我已经尝试过使用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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

我可以使用循环变量或数组来减少我的代码吗

我可以使这个bash脚本更短吗?

我可以使此功能定义更短吗?

我可以使用数组优化此代码以使其在单个循环中处理100页吗?

我可以使用Rcpp加速我的R代码吗?

我可以使用 for 循环来获得相同的结果吗?

我可以使用OTL并行化嵌套循环吗?

我可以使用循环声明数组吗?

我可以使用 for 循环来创建类吗?

我可以使用break退出多个嵌套的“ for”循环吗?

我们可以使用无条件循环吗?

我可以使用常量结构进行循环引用吗?

我可以使用循环使此迭代更容易吗?

我可以使用FSI调试代码吗?

我可以使用代码按回车键吗?

我可以使我的angular-ui-router stateProvider定义更短吗?

我可以使用java.util.LinkedList构造循环/循环链接列表吗?

我有一个for循环来创建列表,我可以使用列表理解吗?

可以使用循环使此代码简短吗?(查看详细信息)

我们可以使用列表理解来处理所使用的 for 循环之外的变量吗?

我可以使用函数式 API 在模型中使用循环吗?

我可以使用并行版本的 for 循环和 apply family 一起使用吗?

可以使此代码更具Pythonic吗?循环

我可以使用对象的单击命令,使用继承来删除重复代码吗?

有什么办法可以使这小段代码更短?(蟒蛇)

有什么办法可以使这段代码更短?

我可以使用通配符替换吗

骨骼可以使用我的插件吗?

我可以使用多个“ with”吗?