简体   繁体   English

python中的集合元素必须是可变的还是不可变的?

[英]elements of sets in python must be mutable or immutable?

I was reading sets in python http://www.python-course.eu/sets_frozensets.php and got confusion that whether the elements of sets in python must be mutable or immutable? 我正在阅读python http://www.python-course.eu/sets_frozensets.php中的集合,并且混淆了python中的集合元素是否必须是可变的或不可变的? Because in the definition section they said "A set contains an unordered collection of unique and immutable objects." 因为在定义部分他们说“一个集合包含一个无序的独特和不可变对象的集合。” If it is true than how can a set contain the list as list is mutable? 如果它是真的,那么集合如何包含列表是可变的?

Can someone clarify my doubt? 有人可以澄清我的怀疑吗?

>>> x = [x for x in range(0,10,2)]
>>> x
[0, 2, 4, 6, 8]      #This is a list x
>>> my_set = set(x)  #Here we are passing list x to create a set
>>> my_set
set([0, 8, 2, 4, 6])   #and here my_set is a set which contain the list.
>>> 

When you pass the set() constructor built-in any iterable , it builds a set out of the elements provided in the iterable. 当你传递内置任何iterableset()构造函数时,它会构建一个迭代中提供的元素集。 So when you pass set() a list, it creates a set containing the objects within the list - not a set containing the list itself, which is not permissible as you expect because lists are mutable. 因此,当您传递set()列表时,它会创建一个包含列表中对象的集合 - 而不是包含列表本身的集合,这是不允许的,因为列表是可变的。

So what matters is that the objects inside your list are immutable, which is true in the case of your linked tutorial as you have a list of (immutable) strings. 所以重要的是列表中的对象是不可变的,在链接教程的情况下也是如此,因为你有一个(不可变的)字符串列表。

>>> set(["Perl", "Python", "Java"])
set[('Java', 'Python', 'Perl')]

Note that this printing formatting doesn't mean your set contains a list, it is just how sets are represented when printed. 请注意,此打印格式并不意味着您的集合包含列表,而是打印时表示集合的方式。 For instance, we can create a set from a tuple and it will be printed the same way. 例如,我们可以从元组创建一个集合,它将以相同的方式打印。

>>> set((1,2,3))
set([1, 2, 3])

In Python 2, sets are printed as set([ comma-separated-elements ]) . 在Python 2中,集合打印为set([ comma-separated-elements ])

You seem to be confusing initialising a set with a list: 你似乎混淆初始化一个列表集:

a = set([1, 2])

with adding a list to an existing set: 将列表添加到现有集合:

a = set()
a.add([1, 2])

the latter will throw an error, where the former initialises the set with the values from the list you provide as an argument. 后者将抛出一个错误,前者使用您提供的列表中作为参数初始化集合。 What is most likely the cause for the confusion is that when you print a from the first example it looks like: 什么是最有可能的混乱的原因是,当你打印a从第一个例子,它看起来像:

set([1, 2])

again, but here [1, 2] is not a list, just the way a is represented: 再次,但这里[1, 2]不是一个列表,只是表示a的方式:

a = set()
a.add(1)
a.add(2)
print(a)

gives: 得到:

set([1, 2])

without you ever specifying a list. 没有你指定一个列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM