【问题标题】:How to receive bare strings from a dictionary, without double quotes or brackets or parenthesis at the end?如何从字典中接收裸字符串,末尾没有双引号或括号或括号?
【发布时间】:2019-12-17 16:49:55
【问题描述】:

给定字典,我如何从字典中获取“原始”值列表?所需的结果在末尾不包含括号或括号或双引号,它只包含每个值的单引号。期望的结果如下所示:

result = 'yellow', 'green', 'white'

我愿意接受有关如何设置字典以轻松获得所需结果输出的建议。字典可以由键值对组成,其中键值对是字典和列表或元组或集合。

此解决方案在测试中有效,我想知道是否有比使用 print 更 Python 和更强大的东西,以便我可以使用结果,而不仅仅是在测试中打印出来:

Dict_w_tuple_values = dict(
   dictionary={
    'fruits':{
        'type':['c'],
        'colors':('yellow', 'green', 'white'),
    },
)

result = print(", ".join( repr(e) for e in list(Dict_w_tuple_values['dictionary']['fruits']['colors'])))

原来我有这本词典:

Dict_w_list_values = dict(
   dictionary={
    'fruits':{
        'type':['c'],
        'colors':['yellow', 'green', 'white'],
    },
)

...并尝试了列表推导,.joineval(list_object).strip.lstripfindallstr(list_object)[1:-1]re.subreplace,@9876543334@ 和 @987654@3 .

这些都没有奏效。我看到了一些使用正则表达式的机会,但没有得到想要的结果。

最终,我想使用结果来填充参数 .format(**Dict_w_tuple_values)

填充时的参数应该是:

'yellow', 'green', 'white'

不是

"'yellow', 'green', 'white'"

["'yellow', 'green', 'white'"]

也没有

("'yellow', 'green', 'white'")

【问题讨论】:

  • 您没有列表对象。你有一个字符串

标签: python dictionary object quotes strip


【解决方案1】:

使用替换功能从列表中删除 []。 以下是供您参考的代码。

a.replace('[','').replace(']','')

双引号使列表变为字符串,因此我们无法删除它。让我知道使用双引号的原因,我们可以解决这个问题

【讨论】:

  • 你好 Muraldihar,谢谢你的建议。我已经更新了描述。我希望它能更好地解释代码的需求和目的。
【解决方案2】:

与其获取list_object 字符串并对其应用正则表达式,不如这样做?

list_string = ', '.join(DictVariables['dictionary']['fruits']['colors'])

如果您需要在每个字符串周围加上单引号:

list_string = "'{}'".format(
    "', '".join(DictVariables['dictionary']['fruits']['colors']))

这会在每个元素之间添加单引号 (', '),然后使用 format 添加剩余的外部引号

【讨论】:

  • 嗨,亚历克斯,谢谢。这是一个更直接的解决方案。再次测试后,我发现我确实需要在每个颜色值周围加上单引号。您能否推荐如何使用您的方法,同时只保留颜色值周围的单引号?
  • 这很接近。 result = ', '.join(DictVariables['dictionary']['fruits']['colors']) >>> 'yellow, green, white' result = "'{}'".format( "', '".join(DictVariables['dictionary']['fruits']['colors'])) >>> "'yellow', 'green', 'white'" result = "', '".join(DictVariables['dictionary']['fruits']['colors'])) >>> "yellow', 'green', 'white"
猜你喜欢
  • 2011-01-12
  • 2014-09-26
  • 1970-01-01
  • 2012-01-28
  • 1970-01-01
  • 2021-06-12
  • 2020-07-13
  • 2022-07-06
相关资源
最近更新 更多