Проверьте, начинается ли строка с любого элемента в кортеже, если True, верните этот элемент - PullRequest
0 голосов
/ 11 марта 2020

У меня есть кортеж значений следующим образом:

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

Я получаю ввод от пользователя и проверяю, совпадает ли ввод с любым значением в кортеже, следующим образом:

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

То, что я хотел бы сделать, точно так же, как указано выше, но с возвращенным соответствующим элементом. Я перепробовал много методов, но ничего не получалось. Заранее спасибо.

Редактировать: В какой-то момент я подумал, что мог бы использовать оператор Моржа, но вы бы поняли, что это не сработает.

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

Ответы [ 3 ]

1 голос
/ 11 марта 2020

Эта функция принимает функцию с одним аргументом и списком аргументов и возвращает первый аргумент, который заставляет функцию возвращать истинное значение. В противном случае возникнет ошибка:

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)
0 голосов
/ 11 марта 2020

Вы можете использовать any.

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

Если вы хотите запросить ввод данных пользователем до тех пор, пока их ответ не будет действительным, введите это время l oop.

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.
# ...
0 голосов
/ 11 марта 2020

Попробуй это. Вы можете хранить свои функции в словаре и вызывать их.

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)

output:

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