在Java中可以将列表添加到集合,但在Python中不可以?

2024-10-01 19:15:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我是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有何不同,以及在编写上述代码时是否需要注意一些问题。你知道吗


Tags: 代码add概念newstringjava中将list
1条回答
网友
1楼 · 发布于 2024-10-01 19:15:28

列表在python中是不可修改的,因为它们没有定义__hash__。这是有原因的,但是可以想象,您可以定义自己的可变类,只要所述散列不会在对象的整个生命周期中改变。例如,使用id(x)作为哈希。事实上,您可能已经在自己的许多类中不知不觉地实现了这一点。你知道吗

我将引用docs中关于“hashable”的内容:

All of Python’s immutable built-in objects are hashable, while no mutable containers (such as lists or dictionaries) are. Objects which are instances of user-defined classes are hashable by default; they all compare unequal (except with themselves), and their hash value is their id().

可变性和散列性是耦合的,但不是一回事。你知道吗

相关问题 更多 >

    热门问题