python variable name_python variable name change

I have a bit of question with python.

I have a piece of code

screen.blit(badninja1,(badninja1px ,badninja1py))

screen.blit(badninja2,(badninja2px ,badninja2py))

screen.blit(badninja3,(badninja3px ,badninja3py))

I know it repeats 3 time and I want to do some refactoring.

That is a piece of python code

what it does was draw badninja1 at location badninja1px and badninja1py etc.

bandninja1, badninja1px, badninja1py and other are variable names.

I wanted to put this code in a for loop

for x in range(1, 4):

#add number 1, 2, 3 to the variable name.

I tried to do that and realized that I can combine string easily in python:

"Dec "+str(25)+"th".

However, changing variable name is a bit tricky.

Can anybody give ma a hint thanks!!

解决方案

You'd normally keep those values in lists or dictionaries instead:

badninjas = [badninja1, badninja2, badninja3]

and keep information like their location with the badninja objects:

for ninja in badninjas:

screen.blit(ninja, (ninja.px, ninja.py))

You can look up variables dynamically, using either the globals() or locals() results (both return a mapping) but generally speaking you should avoid such behaviour. It certainly shouldn't be needed here.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值