如何使用 Python 集合并将字符串作为字典值添加到其中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24654183/
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 04:57:41  来源:igfitidea点击:

How to use Python sets and add strings to it in as a dictionary value

pythondictionaryset

提问by 12avi

I am trying to create a dictionary that has values as a Set object. I would like a collection of unique names associated with a unique reference). My aim is to try and create something like:

我正在尝试创建一个将值作为 Set 对象的字典。我想要一组与唯一引用关联的唯一名称)。我的目标是尝试创建类似的东西:

AIM:

目的:

Dictionary[key_1] = set('name')    
Dictionary[key_2] = set('name_2', 'name_3')

Adding to SET:

添加到 SET:

Dictionary[key_2].add('name_3')

However, using the set object breaks the namestring into characters which is expected as shown here. I have tried to make the string a tuple i.e. set(('name'))and Dictionary[key].add(('name2')), but this does not work as required because the string gets split into characters.

然而,使用设定的对象打破了name字符串转换成如图所示预计字符在这里。我试图使字符串成为元组 ie set(('name'))and Dictionary[key].add(('name2')),但这不能按要求工作,因为字符串被拆分为字符。

Is the only way to add a string to a set via a list to stop it being broken into characters like

是通过列表将字符串添加到集合以阻止它被分解为字符的唯一方法

'n', 'a', 'm', 'e'

Any other ideas would be gratefully received.

任何其他想法将不胜感激。

采纳答案by Duncan

You can write a single element tuple as @larsmans explained, but it is easy to forget the trailing comma. It may be less error prone if you just use lists as the parameters to the set constructor and methods:

您可以按照@larsmans 的解释编写单个元素元组,但很容易忘记尾随逗号。如果您仅使用列表作为 set 构造函数和方法的参数,则可能不太容易出错:

Dictionary[key_1] = set(['name'])    
Dictionary[key_2] = set(['name_2', 'name_3'])

Dictionary[key_2].add(['name_3'])

should all work the way you expect.

应该都按照你期望的方式工作。

回答by Fred Foo

('name')is not a tuple. It's just the expression 'name', parenthesized. A one-element tuple is written ('name',); a one-element list ['name']is prettier and works too.

('name')不是元组。这只是'name'括号中的表达式。一个单元素元组被写入('name',);单元素列表['name']更漂亮并且也有效。

In Python 2.7, 3.x you can also write {'name'}to construct a set.

在 Python 2.7、3.x 中,您还可以编写{'name'}来构造一个集合。