如何通过用户输入在字典中创造价值?

时间:2019-05-10 12:41:26

标签: python python-3.x dictionary

我有一个函数,该函数创建一个请求以将客户端发送到我的服务器。 客户端获得一个菜单,并且对于每个选项,该函数都会创建一个发送到服务器的请求,但是对于某些选项,必须包含用户的输入,我尝试制作一个具有8个键和一些值的字典。其中的-是“ input()”。 问题是,如果我这样做,它会询问一次所有键的输入,但是我只想为特定键创建值。 这是我尝试过的:

def input():
    print("1 - Albums list\n2 - List of songs in a album\n3 - Get song length")
    print("4- Get lyrics song\n5 - Which album is the song in?")
    print("6 - Search Song by Name\n7 - Search Song by Lyrics in Song\n8 - Exit")
    request_creator(input())

def request_creator(x):
    return {'1': "1#", '2': "2#" + input("Enter album: "), '3': "3#" + input("Enter song: "), '4': "4#" + input("Enter song: "), '5': "5#" + input("Enter song: "), '6': "6#" + input("Enter a word: "), '7': "7#" + input("Enter lyrics: "), '8': "8#"}[x]

例如,当用户要求选项3时,它也会要求他提供所有其他值,但我只需要键3。 没有很多if语句,有没有办法做到这一点?

1 个答案:

答案 0 :(得分:4)

首先,我建议为input函数选择一个不同的名称。如果要继续使用内置的input,则不得使用自己的函数覆盖其名称。 get_input呢?

防止字典立即调用所有input的一种方法是将每个值包装在lambda中。这将使每个值成为一个匿名函数对象,除非显式调用它们,否则它们均不会执行。

def get_input():
    print("1 - Albums list\n2 - List of songs in a album\n3 - Get song length")
    print("4- Get lyrics song\n5 - Which album is the song in?")
    print("6 - Search Song by Name\n7 - Search Song by Lyrics in Song\n8 - Exit")
    x = request_creator(input())
    print(x)

def request_creator(x):
    return {
        '1': lambda: "1#", 
        '2': lambda: "2#" + input("Enter album: "), 
        '3': lambda: "3#" + input("Enter song: "), 
        '4': lambda: "4#" + input("Enter song: "), 
        '5': lambda: "5#" + input("Enter song: "), 
        '6': lambda: "6#" + input("Enter a word: "), 
        '7': lambda: "7#" + input("Enter lyrics: "), 
        '8': lambda: "8#"
    }[x]()

get_input()

结果:

1 - Albums list
2 - List of songs in a album
3 - Get song length
4- Get lyrics song
5 - Which album is the song in?
6 - Search Song by Name
7 - Search Song by Lyrics in Song
8 - Exit
3
Enter song: hey jude
3#hey jude

如果您对使用lambda感到不满意,可以改为将每个提示的文本存储在字典中(如果该选项不需要提示,则将其存储在字典中)。然后,您可以获取该字符串并使用它来调用input(或完全跳过调用input)。

def get_input():
    print("1 - Albums list\n2 - List of songs in a album\n3 - Get song length")
    print("4- Get lyrics song\n5 - Which album is the song in?")
    print("6 - Search Song by Name\n7 - Search Song by Lyrics in Song\n8 - Exit")
    x = request_creator(input())
    print(x)

def request_creator(x):
    prompts = {
        '1': None,
        '2': "Enter album: ",
        '3': "Enter song: ",
        '4': "Enter song: ",
        '5': "Enter song: ",
        '6': "Enter a word: ",
        '7': "Enter lyrics: ",
        '8': None
    }
    result = x + "#"
    prompt = prompts[x]
    if prompt is not None:
        result += input(prompt)
    return result

get_input()