小编New*_*bie的帖子

打印不带字典名称的字典键?如何/为什么?

所以我创建了一个字典来设置一个小游戏的难度级别.

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:

  1. 我可以在不创建新元素的情况下实现相同的结果,例如diff_keys吗?

  2. 为什么要diff_dict.keys显示字典.名称?难道我做错了什么?

  3. 另外,如何在没有字符串引号(')的情况下打印键或其他元素(如列表,元组等)?

  4. 与上面的#3相同但括号([])

谢谢和cheerio :-)

python printing dictionary key python-3.x

2
推荐指数
1
解决办法
3602
查看次数

在Python中使用范围作为字典键,我有什么选择?

这是我的第一篇文章,我对编程很陌生,所以我可能无法恰当地传达我的问题,但我会尽我所能!

tries_dict = {1:'first', 2:'second', 3:'third', 4:'fourth', ub_tries:'last'}

ub_tries = user input

tries = 1

input ('\nCome on make your ' + tries_dict.get(tries) + guess: ')
Run Code Online (Sandbox Code Playgroud)

这三个元素是我创建的数字猜测游戏的一部分,我将它们包含在每个错误答案之后的while循环中tries += 1.

正如您所看到的,在我的字典中,前4个答案的自定义值和游戏结束前的最后可能机会,所以这是我尝试做的:

我想找到一种方法,在'4th'和'last'之间为每个答案/键设置'NEXT'值.

如:

tries = 5

Come on make your next guess

tries = 6

Come on make your next guess
Run Code Online (Sandbox Code Playgroud)

等等

我确实找到了一种带有复杂循环的方法,但是我想知道更好的/实用的方法来实现这一点.

以下是我想到的一些选项,但无法开始工作:

  1. 使用范围作为关键
  2. 找到一种方法来生成值介于4之间的列表,ub_tries并将该列表用作键

所以一般来说:如何创建一种方法来获得未在字典中指定的键的一般答案(下一个或其他)?

任何反馈都会非常感激,随时可以要求澄清,因为我可以告诉自己我的问题有点混乱.

我希望我在编程和提出相关问题时变得更加狡猾,到目前为止,我的编程几乎和我的总结技巧一样混乱,感叹!

python dictionary loops key range

0
推荐指数
1
解决办法
1万
查看次数

标签 统计

dictionary ×2

key ×2

python ×2

loops ×1

printing ×1

python-3.x ×1

range ×1