How to use Python sets and add strings to it in as a dictionary value(如何使用 Python 集并将字符串作为字典值添加到其中)
问题描述
我正在尝试创建一个将值作为 Set 对象的字典.我想要一组与唯一引用关联的唯一名称).我的目标是尝试创造类似的东西:
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:
目标:
Dictionary[key_1] = set('name')
Dictionary[key_2] = set('name_2', 'name_3')
添加到 SET:
Dictionary[key_2].add('name_3')
但是,使用 set 对象将 name 字符串分解为预期的字符,如 这里.我试图使字符串成为一个元组,即 set(('name')) 和 Dictionary[key].add(('name2')),但这确实无法按要求工作,因为字符串被拆分为字符.
However, using the set object breaks the name string 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.
是通过列表将字符串添加到集合以阻止它被分解成字符的唯一方法
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.
推荐答案
你可以像@larsmans 解释的那样写一个单元素元组,但是很容易忘记结尾的逗号.如果您只使用列表作为 set 构造函数和方法的参数,则可能不太容易出错:
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:
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.
这篇关于如何使用 Python 集并将字符串作为字典值添加到其中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用 Python 集并将字符串作为字典值添加到其中
基础教程推荐
- Discord.py 缺少必需的参数 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
