python - 如何在列表中查找特定项目并使用该项目执行操作

标签 python list input

我非常擅长 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

有什么想法吗?

谢谢

最佳答案

使用字典,以字符串为键,函数为值:

todos = {
  'thing1': do_something,
  'thing2': do_something_else,
  'thing3': do_something_different,
}

item = input('type your item here')
todos.get(item, lambda: None)()

关于python - 如何在列表中查找特定项目并使用该项目执行操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29927482/

相关文章:

python - 非缓冲模式下的 IPython

python - pandas:跨多列搜索部分字符串并输出每行的值

python - 计算列表中单词的频率并删除不受欢迎的单词

android - recyclerview 中的粘性标题/项目

javascript - JS - 列出以逗号分隔的数组

r - 如何使用 Corrplot 与手动创建的相关矩阵(列表类型)

C++ 存储 cin 输入并跳过其他输入

python - 按自定义顺序展平 np.ndarray

html - 输入类型=时间不适用于最小和最大属性

Android,无法使用WebView上传图片