如何创建只有一个元素的 Python 集?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19985145/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 15:09:13  来源:igfitidea点击:

How do I create a Python set with only one element?

pythonpython-3.xset

提问by Thalecress

If I have a string, and want to create a set that initially contains onlythat string, is there a more Pythonic approach than the following?

如果我有一个字符串,并且想创建一个最初包含该字符串的集合,是否有比以下更 Pythonic 的方法?

mySet = set()
mySet.add(myString)

The following gives me a set of the letters in myString:

下面给了我一组 中的字母myString

mySet = set(myString)

采纳答案by dstromberg

In 2.7 as well as 3.x, you can use:

在 2.7 和 3.x 中,您可以使用:

mySet = {'abc'}

回答by Anatoly Scherbakov

For example, this easy way:

例如,这个简单的方法:

mySet = set([myString])

回答by Ashwini Chaudhary

For Python2.7+:

对于 Python2.7+

set_display ::=  "{" (expression_list | comprehension) "}"

Example:

例子:

>>> myString = 'foobar'
>>> s = {myString}
>>> s
set(['foobar'])

>>> s = {'spam'}
>>> s
set(['spam'])

Note that an empty {}is not a set, its a dict.

请注意,空{}不是 a set,而是a dict

Help on set:

帮助set

class set(object)
 |  set() -> new empty set object
 |  set(iterable) -> new set object

As you can see set()expects an iterable and strings are iterable too, so it converts the string characters to a set.

正如您所看到的,set()期望一个可迭代的,而字符串也是可迭代的,因此它将字符串字符转换为一个集合。

Put the string in some iterable and pass it to set():

将字符串放入一些可迭代对象并将其传递给set()

>>> set(('foo',))  #tuple
set(['foo'])
>>> set(['foo'])   #list
set(['foo'])

回答by Simeon Visser

If the set also isn't likely to change, consider using a frozenset:

如果集合也不太可能改变,请考虑使用frozenset

mySet = frozenset([myString])

回答by SzieberthAdam

set(obj)is going to iterate trough objand add all unique elements to the set. Since strings are also iterable, if you pass a string to set()then you get the unique letters in your set. You can put your obj to a list first:

set(obj)将迭代槽obj并将所有唯一元素添加到集合中。由于字符串也是可迭代的,如果您将字符串传递给,set()那么您将获得集合中的唯一字母。您可以先将 obj 放入列表:

set(["mystring"])

However that is not elegant IMO. You know, even for the creation of an empty dictionary we prefer {}over dict(). Same here. I wolud use the following syntax:

然而,这不是优雅的 IMO。要知道,即使是创造我们更喜欢一个空的字典{}dict()。同样在这里。我会使用以下语法:

myset = {"mystring"}

Note that for tuples, you need a comma after it:

请注意,对于元组,后面需要一个逗号:

mytuple = ("mystring",)

回答by matt2000

use mySet = {mystring}

mySet = {mystring}

 Python 3.6.9 (default, Sep 24 2019, 14:35:19)                                                                                             
 Type 'copyright', 'credits' or 'license' for more information                                                                             
 IPython 7.8.0 -- An enhanced Interactive Python. Type '?' for help.                                                                       

 In [1]: def s(i):                                                                                                                         
     ...:     r = set()                                                                                                                     
     ...:     r.add(i)                                                                                                                      
     ...:     return r                                                                                                                      
     ...:                                                                                                                                   

 In [2]: %timeit s(1234)                                                                                                                   
  218 ns ± 5.99 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)                                                                

 In [3]: %timeit set([1234])                                                                                                               
  201 ns ± 3 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)                                                                  

 In [4]: %timeit {1234}                                                                                                                    
  51.7 ns ± 1.7 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)