Python中文
首页
教程
问答
标签
搜索
登录
注册
如何存储并调用同一字典中的字符串和函数?
回答此问题可获得
20
贡献值,回答如果被采纳可获得
50
分。
<p>我一直在尝试在字典中存储并调用字符串和/或函数</p> <h3 id="first-example-sxba">第一个示例</h3> <pre><code>def mainfunction(): dict = { 'x' : secondfunc, 'y' : 'hello world' } while True : inpt = input('@') dict[inpt]() def secondfunc(): print('hi world') mainfunction() </code></pre> <p>仅当我输入键“x”时,此操作才有效。 如果我尝试输入键“y”,我会得到这个错误</p> <pre class="lang-none prettyprint-override"><code>TypeError: 'str' object is not callable </code></pre> <p>另外,这个方法的问题是它不能给出默认答案</p> <h3 id="second-example-fbnu">第二个示例</h3> <pre><code>def mainfunction(): dict = { 'x' : secondfunc, 'y' : 'hello world' } while True: inpt = input('@') z = dict.get(inpt, 'Default text') print(z) def secondfunc(): print('hi world') mainfunction() </code></pre> <p>此方法适用于键“y”,但对于键“x”,它会打印出以下内容:</p> <pre class="lang-none prettyprint-override"><code><function secondfunc at 0x7ab4496dc0> </code></pre> <p>我试图使它,无论我输入哪个值,它将打印一个默认值,打印一个字符串,或执行一个函数。所有这些都取决于按键输入</p> <h3 id="last-example-i9h1">最后一个示例</h3> <p>我找到的唯一解决方案是使用<code>if</code>语句</p> <pre><code>def mainfunction(): dict = { 'x' : secondfunc, } dict2 = { 'y' : 'hello world' } while True: inpt = input('@') z = dict2.get(inpt, 'Default text') if inpt == 'x': dict[inpt]() else: print(z) def secondfunc(): print('hi world') mainfunction() </code></pre> <p>这个解决方案需要的代码比我希望的要多,而且它还需要特定于给定字典的<code>if</code>语句,这需要更多的时间。 难道没有更好的办法吗</p>
0 条评论
分类:
Python问答
请先
登录
后评论
默认排序
时间排序
1 个回答
匿名
1天前
擅长:python、mysql、java
<p>您可以使用<code>callable()</code>内置函数测试给定对象是否可调用</p> <pre><code>z = dict2.get(inpt, 'Default text') if callable(z): z() else: print(z) </code></pre>
请先
登录
后评论
针对此问题:
更多的回答
关注
89
关注
收藏
1
收藏,
216
浏览
网友 提问于 2天前
相关Python问题
当pandas中出现小数据时,DataFrame.resample()被调用时,内存不足
5 回答
当Pandas中存在许多条件时,如何过滤数据?
5 回答
当pandas中没有公共列名时,我们应该如何组合多个数据集而不在行或列中重复
6 回答
当pandas中的值为null时,不使用pandas的to_列表
2 回答
当Pandas中的值和条目匹配时,如何计算键的计数?
9 回答
当pandas列中有字符串时,如何从该列获取最长长度的string/integer/float
3 回答
当pandas列重命名创建列名重复时该怎么办
3 回答
当Pandas在带有颜色标签的多个子图中创建散点图时,无法设置xlabel
2 回答
当pandas导入openpyxl模块时,该模块没有属性''uuuversion''
3 回答
当pandas数据在python中聚合时,如何计算每组尾部的sum | mean |中值
7 回答
当Pandas数据头以列(如xls)拆分时,如何读取Pandas数据头
8 回答
当Pandas数据帧包含nan时,用“新信息”更新Pandas数据帧
2 回答
当pandas是imp时,Cx\u freeze TypeError只能使用numpy依赖项将list(而不是“NoneType”)连接到list
10 回答
当Pandas满足一定条件时,如何放弃整个群体
4 回答
当Pandas的时间增量指数不规则时,如何获得时间序列值的日差?
1 回答
当Pandas通过read\u csv方法读取大文件时。IOError:[Errno 13]权限被拒绝
8 回答
当panda列有空值时,如何将其转换为int?
5 回答
当param=''时使用Beautiful Soup访问属性的参数
1 回答
当paramiko抛出“无现有会话”异常时,标准输入流挂起
2 回答
当parentchild在同一端口上监听时会发生什么?
5 回答