我正在编写一个使用Python将函数转换为等效字的函数,反之亦然。
一个功能完成,混乱是关于第二个。为此,我可以使用两个字典,其中键和值对互换,但我想知道我是否可以为这两个函数使用单个字典?
我试过某种方式,但我的回答与列表顺序不一致。如果有办法按照上述顺序获取列表,请告诉我。
这是我的代码:
['8', '2', '4']
two four eight
当前输出:
['8', '2', '4']
eight two four
期望的输出:
public class balloongame extends ApplicationAdapter {
SpriteBatch batch;
Texture background;
Texture balloon;
private float renderX;
@Override
public void create () {
batch = new SpriteBatch();
background = new Texture("bg.png");
balloon = new Texture("final.png");
renderX = 100;
}
@Override
public void render () {
renderX += Gdx.input.getAccelerometerX();
if(renderX < 0) renderX = 0;
if(renderX > Gdx.graphics.getWidth() - 200) renderX = Gdx.graphics.getWidth() - 200;
batch.begin();
batch.draw(background, 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
batch.draw(balloon,renderX, Gdx.graphics.getWidth());
batch.end();
}
@Override
public void dispose () {
batch.dispose();
}
答案 0 :(得分:0)
我认为这就是你想要的
nDict={"0":"zero","1":"one","2":"two","3":"three","4":"four","5":"five","6":"six","7":"seven","8":"eight","9":"nine"}
def printNumbers(numbers):
print(list(numbers))
print(' '.join(map(nDict.get, numbers)))
如果更改字典的顺序,则可以将字符用作单词的键,而不是反之。
更新以使用相同的字典 注意,10由2个字符组成,因此它们不完全相同 - 而不是10个,你将有一个零
nDict={"zero":"0", "one":1,"two":2,"three":3,"four":4,"five":5,"six":6,"seven":7,"eight":8,"nine":9}
def integerToString(answer):
myAnsList=list(answer)
print(myAnsList)
myAnsWordList=[]
for num in myAnsList:
for k,i in nDict.items():
if str(i) == num:
myAnsWordList.append(k)
myAnsString=' '.join(myAnsWordList)
print(myAnsString)
integerToString('824')
更新2:
根据评论,字典可以反转并加快转换
nDict={"zero":"0", "one":1,"two":2,"three":3,"four":4,"five":5,"six":6,"seven":7,"eight":8,"nine":9}
revNDict = { str(v): k for k, v in nDict.items() }
def printNumbers(numbers):
print(list(numbers))
print(' '.join(map(revNDict.get, numbers)))