我是Python新手,刚刚无意中将list
添加到了set
。现在我知道了reason为什么这是不可能的,因为list
是可变的,所以它的hashcode
(或者Python对应的概念)会改变。回想我用Java编程的经历,我发现我已经做过很多次了。你知道吗
HashSet<ArrayList<String>> masterCollection = new HashSet<ArrayList<String>>();
ArrayList<String> a = new ArrayList<String>();
masterCollection.add(a);
a.add("Hello, World");
for(ArrayList<String> list : masterCollection) {
// do something to list
}
我没有注意到上述代码的任何异常行为。我甚至用ArrayList
作为HashMap
的键,成功地完成了我的任务。你知道吗
因此,我想问一下Python在这方面与Java有何不同,以及在编写上述代码时是否需要注意一些问题。你知道吗
列表在python中是不可修改的,因为它们没有定义
__hash__
。这是有原因的,但是可以想象,您可以定义自己的可变类,只要所述散列不会在对象的整个生命周期中改变。例如,使用id(x)
作为哈希。事实上,您可能已经在自己的许多类中不知不觉地实现了这一点。你知道吗我将引用docs中关于“hashable”的内容:
可变性和散列性是耦合的,但不是一回事。你知道吗
相关问题 更多 >
编程相关推荐