返回项在表中的位置(如果项在表中)。[第3.4页]


cmds = ['time']
while True:
    inp = input('::> ')
    sinp = inp.split()
    if str(sinp[0]) in cmds:
        print('mkay.')

如果名称和输入匹配,我是否能够获取项目在表中的位置?谢谢!

更新:

这是我更新的代码:

cmds = ['k', '1']
while True:
inp = input('>>> ')
sinp = inp.split()
try:
    if str(sinp[0]) in cmds:
        cmds.index(sinp)
        print(sinp)
except ValueError:
    print('Unknown Command')

每当我输入 k 或"k"时,它都会返回"未知命令"。1 也是如此,但"1"有效。这是什么原因呢?

天啊。很抱歉给你们带来麻烦,我只是为 .index 做了 sinp 而不是 sinp[0]。哎哟。

更新:它不接受"1"或1.即使它在CMDS表中。

您可以使用

you_list.index(the_item)

cmds = ['time', 'yep']
while True:
    inp = input('::> ')
    sinp = inp.split()
    if str(sinp[0]) in cmds:
        print('mkay.')
        print cmds.index(inp)

输出:

::> time
mkay.
0
::> yep
mkay.
1
::> 

如果cmds是"表",那么cmds.index会给你匹配字符串的位置。

列表的index()方法是您需要的。

>>> cmds = ['e', 'r', 't']
>>> cmds.index('e')
0
>>> cmds.index('t')
2
>>> cmds.index('y')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: 'y' is not in list

确保将其放在 try 中,except块中,以防找不到该命令。

例如

inp = str(input('::> '))
sinp = inp.split()
print("You are trying to run command:", sinp[0])
try:
    print(cmds.index(sinp[0]))
except ValueError:
    print("Command not recognised")