在什么情况下我会使用元组作为字典键? [英] In what case would I use a tuple as a dictionary key?

查看:122
本文介绍了在什么情况下我会使用元组作为字典键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究列表和元组之间的差异(在Python中).一个明显的例子是,元组是不可变的(在初始赋值后不能更改值),而列表是可变的.

I was studying the difference between lists and tuples (in Python). An obvious one is that tuples are immutable (the values cannot be changed after initial assignment), while lists are mutable.

文章中的一句话吸引了我:

A sentence in the article got me:

只能将不可变元素用作 字典键,因此只有元组 而不是列表可以用作键.

Only immutable elements can be used as dictionary keys, and hence only tuples and not lists can be used as keys.

我很难考虑要使用元组作为字典键的情况.您能否提供一个示例问题,将其作为自然,有效,优雅或显而易见的解决方案?

I have a hard time thinking of a situation where I would like to use a tuple as a dictionary key. Can you provide an example problem where this would be the natural, efficient, elegant, or obvious solution?

感谢您的示例.到目前为止,我认为一个非常重要的应用程序是函数值的缓存.

Thanks for your examples. So far I take that a very important application is the caching of function values.

推荐答案

经典示例:您想将点值存储为(x,y)的元组

Classic Example: You want to store point value as tuple of (x, y)

这篇关于在什么情况下我会使用元组作为字典键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆