How do I create a Python set with only one element

2019-02-07 16:18发布

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

mySet = set()
mySet.add(myString)

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

mySet = set(myString)

5条回答
手持菜刀,她持情操
2楼-- · 2019-02-07 16:52

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

mySet = {'abc'}
查看更多
Viruses.
3楼-- · 2019-02-07 16:55

For example, this easy way:

mySet = set([myString])
查看更多
神经病院院长
4楼-- · 2019-02-07 16:57

set(obj) is going to iterate trough obj and 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(["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:

myset = {"mystring"}

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

mytuple = ("mystring",)
查看更多
你好瞎i
5楼-- · 2019-02-07 17:05

For 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.

Help on 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.

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

>>> set(('foo',))  #tuple
set(['foo'])
>>> set(['foo'])   #list
set(['foo'])
查看更多
倾城 Initia
6楼-- · 2019-02-07 17:11

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

mySet = frozenset([myString])
查看更多
登录 后发表回答