检查字符串是否以元组中的任何元素开头,如果为真,则 return 该元素

Check if a string startswith any element in a tuple, if True, return that element

我有一个值元组如下:

commands = ("time", "weather", "note")

我从用户那里得到一个输入,我检查输入是否匹配元组中的任何值,如下所示:

if user_input.startswith(commands):
    # Do stuff based on the command

我想做的和上面的完全一样,只是返回了匹配项。我尝试了很多方法,但没有任何效果。提前谢谢你。

编辑: 在某些时候,我认为我可以使用 Walrus 运算符,但你会发现它不起作用。

if user_input.startswith(returned_command := commands):
    command = returned_command
    # actually command only gets the commands variable.

试试这个。您可以将函数存储在字典中并调用它们。

def print_time():
    print("Time")

def exit_now():
    exit()

def print_something(*args):
    for item in args:
        print(item)

command_dict = {
    "time": print_time,
    "something": print_something,
    "exit": exit_now
}

while True:
    user_input = input("Input command: ")
    command, *args = user_input.split()
    command_dict[command](*args)

输出:

Input command: time
Time
Input command: something 1 2 3
1
2
3
Input command: exit

您可以使用 any.

user_input = input()
if any(user_input.startswith(s) for s in commands):
    # The input is valid. 

如果您想在用户回复有效之前请求用户输入,请将其放入 while 循环。

match = None

while True:
    user_input = input()
    if any(user_input.startswith(s) for s in commands): # Make sure there is a match at all. 
       for c in commands:
           if user_input.startswith(c):
               match = c # Find which command matched in particular.
               break     # Exit the loop.
    else:
        print(f"Your selection should be one of {commands}.")


# ...
# Do something with the now valid input and matched element.
# ...

此函数接受一个参数的函数和一个参数列表,并将 return 使函数 return 成为真值的第一个参数。否则,它会引发错误:

def first_matching(matches, candidates):
    try:
        return next(filter(matches, candidates))
    except StopIteration:
        raise ValueError("No matching candidate")

result = first_matching(user_input.startswith, commands)