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

2024-09-27 21:34:55 发布

您现在位置:Python中文网/ 问答频道 /正文

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表中。你知道吗


Tags: in名称trueinputindexiftimesplit
3条回答

list的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

确保将它放在tryexcept块中,以防找不到该命令。你知道吗

例如

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")

您可以使用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会给出匹配字符串所在的位置。你知道吗

相关问题 更多 >

    热门问题