简体   繁体   中英

Python: Using variable in for loop for substitution

I'm trying to condense repetition in a Python program that utilizes pygame. I currently have some number of lines that are like this:

if pygame.key.get_pressed()[pygame.K_q]: q.PerformNote()
if pygame.key.get_pressed()[pygame.K_w]: w.PerformNote()
if pygame.key.get_pressed()[pygame.K_e]: e.PerformNote()
if pygame.key.get_pressed()[pygame.K_r]: r.PerformNote()
if pygame.key.get_pressed()[pygame.K_t]: t.PerformNote()

I would like to achieve something like this:

keyList = ['q', 'w', 'e', 'r', 't']
for currentKey in keyList:
    if pygame.key.get_pressed()[pygame.K_currentKey]:
        currentKey.PerformNote()

The resulting error is

AttributeError: 'module' object has no attribute 'K_currentKey'

I think I might have spent too much time in BASH recently as this construct makes perfect sense to my brain. I've searched around with no idea of the proper way to implement this.

Map pygame keys to their corresponding variables:

keyMap = {
    pygame.K_q: q,
    pygame.K_w: w,
    pygame.K_e: e,
    pygame.K_r: r,
    pygame.K_t: t,
}

Then you can do:

pressed = pygame.key.get_pressed()
for key, toProc in keyMap.items():
    if pressed[key]:
        toProc.PerformNote()

if you want to retrieve a class member from a string with its name then try:

keyList = ['q', 'w', 'e', 'r', 't']
for currentKey in keyList:
    if pygame.key.get_pressed()[getattr(pygame, 'K_' + currentKey)]:
        currentKey.PerformNote()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM