I have to return a symbol from a dictionary of lists when I am given a [x, y] coordinate. The dictionary of lists is this :
GOBBLET_REPRESENTATION = {
1: ["▫", "◇", "◯", "□"],
2: ["▪", "◆", "●", "■"],
}
Here is what I tried:
def formate_gobblet(gobblet):
if gobblet == []:
return " "
else:
if gobblet == [1,0]:
return f' {GOBBLET_REPRESENTATION.get(1)[0]} '
elif gobblet == [1,1]:
return f' {GOBBLET_REPRESENTATION.get(1)[1]} '
elif gobblet == [1,2]:
return f' {GOBBLET_REPRESENTATION.get(1)[2]} '
elif gobblet == [1,3]:
return f' {GOBBLET_REPRESENTATION.get(1)[3]} '
elif gobblet == [2,0]:
return f' {GOBBLET_REPRESENTATION.get(2)[0]} '
elif gobblet == [2,1]:
return f' {GOBBLET_REPRESENTATION.get(2)[1]} '
elif gobblet == [2,2]:
return f' {GOBBLET_REPRESENTATION.get(2)[2]} '
elif gobblet == [2,3]:
return f' {GOBBLET_REPRESENTATION.get(2)[3]} '
Having formate_gobblet(gobblet) with gobblet = [1,2] should return ◯ . This code does that but, I was wandering if there was a way to make my code simpler for the else statement since it looks like this could be resolved using a loop.
CodePudding user response:
You do not need a loop for this. In fact, this can be done in one line using indexing itself.
def formate_gobblet(gobblet):
if gobblet == []:
return " "
else:
return return f' {GOBBLET_REPRESENTATION.get(gobblet[0])[gobblet[1]]} '
What the code above does is it checks for an empty gobblet
otherwise returns the representation which is at the position pointed by the first element gobblet[0]
and the second element gobblet[1]
CodePudding user response:
because every line is much different, it might be more work to make it with a loop. sorry.