【问题标题】:How to print list with " { list } " brackets如何使用“ { list } ”括号打印列表
【发布时间】:2018-03-12 17:18:52
【问题描述】:

我正在尝试打印带有 {} 大括号的 list。 例如:

the_list = [1, 2, 3]

我想将列表打印为

{1, 2, 3}

我该怎么做? 谢谢!

【问题讨论】:

  • 不要在 python 中列出list。它覆盖了内置的list
  • 另外,如果您列表中的所有值都是唯一的,您可以print(set(your_list)) ;)

标签: python python-3.x


【解决方案1】:

你可以这样做:

print('{' + ', '.join([str(x) for x in the_list]) + '}')

', '.join', ' 连接每个元素

[str(x) for x in the_list] 使每个数字成为一个字符串,因此可以像上面那样连接它。

【讨论】:

  • 更短:'{' + ', '.join(map(str, the_list)) + '}'.
  • 并非如此:我正在尝试向 Python 初学者介绍高阶函数 :)
  • 尽量不要连接字符串,因为它会影响可读性并且存在性能不佳的问题(一旦连接超过 2 个字符串!)
【解决方案2】:

在 Python 2 中,尝试:

my_list = [1, 2, 3]
print '{{{}}}'.format(', '.join(map(str, my_list)))

在 Python 3 中,尝试:

my_list = [1, 2, 3]
print(f'{{{", ".join(map(str, my_list))}}}')

解释:

格式

如果您希望获取特定格式的对象之一,请查看.format() https://docs.python.org/2/library/stdtypes.html#str.format

它使用{} 作为占位符(可以变得更复杂,这只是一个简单的示例)。为了逃避{},只需将其翻倍,就像这样:"{{ }}"。后面这个字符串,在格式化之后,会变成"{ }"

在 Python 3 中,您现在拥有 f 字符串 https://www.python.org/dev/peps/pep-0498/ 它们的工作方式与''.format() 相同,但更具可读性:''.format() => f''

将元素转换为 str

然后,您希望将所有元素(在 list 中)转换为字符串 -> map(str, my_list)

加入元素

然后,您希望将这些元素中的每一个与", " 粘合在一起。在 Python 中,有一个函数可以做到这一点:https://docs.python.org/2/library/stdtypes.html#str.join

', '.join(my_iterable) 会做到的。

保留关键字

最后但同样重要的是,不要将您的列表命名为list。否则,您将重写内置的list,您将无法再使用lists。 检查此答案以获得这些关键字的良好列表:https://stackoverflow.com/a/22864250/8933502

【讨论】:

  • 问题标记为 3.x,所以添加 3.x 所需的括号。
  • @TerryJanReedy 刚刚意识到这一点。我添加了 Python 3 答案。感谢您指出了这一点! :-)
【解决方案3】:

print(str(list).replace('[','{').replace(']','}'))

这会将列表转换为字符串并将“[]”替换为“{}”

【讨论】:

  • 这是对列表表示的 hack。请改用列表中的项目。
  • 这适用于 op 所以它足够好...简单的问题简单的答案不需要复杂@SamuelGIFFARD
  • 3.x 问题应该得到 3.x 的答案
  • @9000 不,它更快。我用timeit测量。对于 3 的短名单,这种方法需要 GIFFARDS 地图答案所需时间的 3/4。对于长列表(10000),优势增长到时间的 1/2(快两倍)。
  • 至少有人提供了一些实际证据,这证明我的尝试是正确的;)感谢@TerryJanReedy 提供的信息
【解决方案4】:

如果你想搞怪:

>>> l = [1, 2, 3]
>>> '{%s}' % str(l).strip('[]')
>>> {1, 2, 3}

【讨论】:

    【解决方案5】:

    有两种方法可以回答这个问题:

    A.通过将 [] 替换为 {} 来修改 str(alist)。 @Garret 修改了 str 结果调用 str.replace 两次。另一种方法是使用 str.translate 同时进行这两项更改。第三种,也是我发现的最快的方法,是切掉 [ 和 ],保留内容,然后添加 { 和 }。

    B.计算 str(alist)[1:-1] 计算的内容,但使用 Python 代码并将结果嵌入 {...} 中。使用 CPython,为构建内容字符串而提出的多个替换要慢得多:

    import timeit
    
    expressions = (  # Orderd by timing results, fastest first.
        "'{' + str(alist)[1:-1] + '}'",
        "str(alist).replace('[','{').replace(']','}')",
        "str(alist).translate(table)",
        "'{' + ', '.join(map(str, alist)) + '}'",
        "'{{{}}}'.format(', '.join(map(str, alist)))",
        "'{' + ', '.join(str(c) for c in alist) + '}'",
        )
    
    alist = [1,2,3]
    table = str.maketrans('[]', '{}')
    for exp in expressions:
        print(eval(exp))  # Visually verify that exp works correctly.
    
    alist = [1]*100  # The number can be varied.
    n =1000
    for exp in expressions:
        print(timeit.timeit(exp, number=n, globals=globals()))
    

    在 Windows 10 上使用 64 位 3.7.0b2 的结果:

    {1, 2, 3}
    {1, 2, 3}
    {1, 2, 3}
    {1, 2, 3}
    {1, 2, 3}
    {1, 2, 3}
    0.009153687000000021
    0.009371952999999988
    0.009818325999999988
    0.018995990000000018
    0.019342450999999983
    0.028495214999999963
    

    1000 和 10000 的相对结果大致相同。

    编辑:@Mike Müller 独立发布了切片表达式,嵌入在以下两个表达式中,其时序与上面的顶部表达式基本相同。

    "f'{{{str(alist)[1:-1]}}}'",
    "'{%s}' % str(alist)[1:-1]",
    

    【讨论】:

      【解决方案6】:
      ('{}'.format(the_list)).replace('[','{').replace(']','}')
      

      结果

      {1, 2, 3}
      

      【讨论】:

      • 这行得通,但让我们面对现实吧,这是一种糟糕的做法。
      • @9000: 反正整件事情都很奇怪。
      • 我不这么认为。如果你想使用.format的重型机械,为什么不使用"{{{0}}}".format(', '.join(...))
      • 当然。我对此很坚决。我尽可能使用.format。事实上,只要我可以让我的代码更深奥,我都会这样做。这是诱饵。
      【解决方案7】:

      使用 Python 3.6 f 字符串:

      >>> lst = [1, 2, 3]
      >>> print(f'{{{str(lst)[1:-1]}}}')
      {1, 2, 3}
      

      或者对于 Python format:

      >>> print('{{{}}}'.format(str(lst)[1:-1]))
      {1, 2, 3}
      

      或使用旧的但未弃用的%

      >>> print('{%s}' % str(lst)[1:-1])
      {1, 2, 3}
      

      【讨论】:

        猜你喜欢
        • 2012-01-12
        • 2013-02-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-06-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多