简体   繁体   English

迭代地建立元组集

[英]Iteratively building sets of tuples

I am trying to iteratively build a set of tuples using set.add(tuple) . 我正在尝试使用set.add(tuple)迭代地构建一组元set.add(tuple) The problem is that first tuple does not remain encapsulated as a tuple. 问题在于第一个元组不会保持封装为元组。 Its members enter the set as unique elements. 其成员将集合作为唯一元素输入。

# What I'd like to do
s = set((1,2))
s.add((3,4))
s.add((5,6))

>>>s
>>>{1, 2, (3, 4), (5, 6)}

Of course I can build the whole thing up as a list of tuples and then convert it to a set, but I'd like to know if it is possible to avoid casting from list to set. 当然,我可以将整个内容构建为一个元组列表,然后将其转换为一个集合,但是我想知道是否有可能避免从列表到集合的转换。

# Works with some extra work
l = [(1,2)]
l.append((3,4))
l.append((5,6))
s = set(l)

>>>s
>>>> {(1, 2), (3, 4), (5, 6)}

Thanks. 谢谢。

You should create your set like this: 您应该这样创建集合:

s = {(1, 2)}

If you do not, the set() "constructor" while unpack all elements from your tuple and add them to a new empty set. 如果不这样做,则在从元组中解压缩所有元素并将其添加到新的空集中时, set() “构造函数”。

On Python 2.7 and later, you can use a set literal: 在Python 2.7和更高版本上,可以使用set文字:

s = {(1, 2)}

If you want to use set to make a set whose one element is thing , you do 如果您想使用set来创建一个元素为thing的set,则可以

s = set([thing])

where the argument to set is a 1-element list. 其中要set的参数为1元素列表。 If thing is (1, 2)`, that means you do 如果thing是(1,2)`,则表示您做了

s = set([(1, 2)])

The one-argument set constructor takes an iterable of things to put into the set. 单参数set构造函数将可迭代的事物放入集合中。 In particular, it does not accept an object and create the singleton set containing that object. 特别是,它不接受对象并创建包含该对象的单例集。

You didn't get an error, because tuples are iterable; 您没有得到错误,因为元组是可迭代的。 the set constructor dutifully added each element of the tuple to the set. set构造函数会尽职地将元组的每个元素添加到set中。

Better is to use the constructor {(1,2)} rather than set(((1,2),)) or set([(1,2)]) ; 更好的是使用构造函数{(1,2)}而不是set(((1,2),))set([(1,2)]) the {...} syntax is overloaded to allow creating set instances as well as dict instancess. {...}语法已重载,以允许创建set实例和dict实例。 (but you can't make an empty set this way; in face of ambiguity, python assumes dict ) (但您不能以这种方式进行空设置;面对歧义,python会采用dict

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

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