我非常喜欢python并且不知道如何正确地提出这个问题,所以这里就是这样。
我试图获取用户输入,并使用它来查找列表中的项目,然后让该项目执行某些操作......我不知道该怎么做。
有点像这样:
things = ['thing1','thing2','thing3']
item = input('type your item here')
if item in things == True:
if item == 'thing1':
do something
elif item == 'thing2':
do something else
elif item == 'thing 3':
do something different
任何想法?
由于
答案 0 :(得分:2)
使用字典,字符串作为键,函数作为值:
todos = {
'thing1': do_something,
'thing2': do_something_else,
'thing3': do_something_different,
}
item = input('type your item here')
todos.get(item, lambda: None)()
答案 1 :(得分:0)
就我个人而言,我认为你应该使用一个过滤器来提取一个只有你想要的数组中的项目的数组"做一些事情"然后使用for表达式来做"做某事"与新数组中的每个元素
//in this example I use filter to select all the even numbers in the
//list and compute their square
//here is a list of numbers
array = [1,2,4,5,7]
//use a filter to take only the elements from the list you need
//the elements part of the new array, arrEvens, will be all the
//elements of array that return true in the lambda expression
arrEvens = filter(lambda a : a%2 ==0, array)
//do something (in this case print the square) of all the
//numbers in the new list of elements that passed the filtering
//test
for x in arrEvens:
print(x*x)

希望我能正确理解你的问题,这有帮助。
答案 2 :(得分:0)
Daniel说正确,要使用词典进行待办事项, 如果您有想要为该匹配执行的功能,以防万一 你可以试试这个:
todos = { 'thing1': function1,
'thing2': function2,
'thing3': function3 }
def function1():
"""any operation """
pass
def function2():
"""any operation """
pass
def function3():
""" any operation """
pass
input_val = raw_input("Enter the thing to do")
todos[input_val]()
希望它有所帮助,