def c(stringenter):
last = 1
commandsline = [['a', 'first'], ['b', 'second'], ['c', 'third']]
for commandblock in commandsline:
last = last + 1
if commandblock[0] == stringenter:
realcommand = str(commandblock[1])
elif last == len(commandsline):
realcommand = stringenter
return realcommand
您好!!!这段代码可以找到并返回第二,第三但是找不到第一个如何解决问题?
答案 0 :(得分:3)
索引从0开始,所以你必须改变这样,另一个想法,你应该在最后更新计数器!:
def c(stringenter):
last = 0
commandsline = [['a', 'first'], ['b', 'second'], ['c', 'third']]
for commandblock in commandsline:
if commandblock[0] == stringenter:
realcommand = str(commandblock[1])
elif last == len(commandsline):
realcommand = stringenter
last = last + 1
return realcommand
答案 1 :(得分:3)
虽然@ Damian的回答正确回答了您的问题,但您可能会发现其他两种形式的函数更容易:
def c(stringenter):
commandsline = [['a', 'first'], ['b', 'second'], ['c', 'third']]
for key, cmd in commandsline:
if stringenter == key:
return cmd
return stringenter
或者直接使用字典:
def c(stringenter):
commandsline = {'a': 'first', 'b': 'second', 'c': 'third'}
return commandsline.get(stringenter, stringenter)
答案 2 :(得分:1)
您可以尝试这样的事情:
def c(stringenter):
commandsline = [['a', 'first'], ['b', 'second'], ['c', 'third']]
for commandblock in commandsline:
if commandblock[0] == stringenter:
return commandblock[1]
return stringenter
如果stringenter等于commandblock [0]中的任何一个它返回commandblock [1]
,它会通过你的命令行列表如果找不到它。它返回stringenter。