New*_*bie 2 python printing dictionary key python-3.x
所以我创建了一个字典来设置一个小游戏的难度级别.
diff_dict = {'easy':0.2, 'medium':0.1, 'hard':0.05} # difficulty level dict
Run Code Online (Sandbox Code Playgroud)
键将是难度名称和值,我会用来计算难度的一些比率.
所以我试图找出如何只向用户打印密钥:
print('\nHere are the 3 possible choices: ',diff_dict.keys())
Run Code Online (Sandbox Code Playgroud)
这将打印为:
Here are the 3 possible choices: dict_keys(['hard', 'easy', 'medium'])
Run Code Online (Sandbox Code Playgroud)
显然我不想显示字典名称,所以我继续搜索,我找到了一个有效的解决方案:
diff_keys = diff_dict.keys()
print ('\nHere are the 3 possible choices: ',list(diff_keys))
Run Code Online (Sandbox Code Playgroud)
但我仍然想知道是否有其他方法可以实现这一点,那么为什么等等.所以我在这里使用Qs:
我可以在不创建新元素的情况下实现相同的结果,例如diff_keys吗?
为什么要diff_dict.keys显示字典.名称?难道我做错了什么?
另外,如何在没有字符串引号(')的情况下打印键或其他元素(如列表,元组等)?
与上面的#3相同但括号([])
谢谢和cheerio :-)
Lev*_*sky 10
问题是,在Python 3中,dict的方法keys()不返回列表,而是返回特殊的视图对象.该对象有一个魔术__str__方法,每当你print对象时,它就会在引擎盖下的对象上调用; 因此,对于通过调用创建的视图对象进行keys() __str__定义,以便生成的字符串包含"dict_keys".
找你自己:
In [1]: diff_dict = {'easy': 0.2, 'medium': 0.1, 'hard': 0.05}
In [2]: print('Here are the 3 possible choices:', diff_dict.keys())
Here are the 3 possible choices: dict_keys(['medium', 'hard', 'easy'])
In [3]: diff_dict.keys().__str__()
Out[3]: "dict_keys(['medium', 'hard', 'easy'])"
Run Code Online (Sandbox Code Playgroud)
请注意,99.9%的时间您不需要直接调用此方法,我只是用它来说明工作原理.
通常,当您想要打印某些数据时,您几乎总是希望进行一些字符串格式化.但在这种情况下,简单str.join就足够了:
In [4]: print('Here are the 3 possible choices:', ', '.join(diff_dict))
Here are the 3 possible choices: medium, hard, easy
Run Code Online (Sandbox Code Playgroud)
所以,回答你的问题:
我可以在不创建新元素的情况下实现相同的结果,例如diff_keys吗?
上面显示了一个例子.
为什么diff_dict.keys显示dict.名称?难道我做错了什么?
因为它的__str__方法是这样的.这是"直接"打印对象时必须处理的问题.
如何在没有字符串引号(')的情况下打印键或其他元素,如列表,元组等?
与上面的#3相同但括号([])
打印它们以便__str__不调用它们.(基本上,不要打印它们.)以您喜欢的任何方式构造一个字符串,将数据制作成它,然后打印它.您可以使用字符串格式,以及许多有用的字符串方法.
| 归档时间: |
|
| 查看次数: |
3602 次 |
| 最近记录: |