如何使用"打印列表{list}"括号

时间:2018-03-12 17:18:52

标签: python python-3.x

我试图用list花括号打印{}。 例如:

the_list = [1, 2, 3]

我希望将列表打印为

{1, 2, 3}

我该怎么做? 谢谢!

7 个答案:

答案 0 :(得分:5)

你可以这样做:

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

', '.join将每个元素与', '

连接起来

[str(x) for x in the_list]使每个数字成为一个字符串,因此可以按上述方式连接。

答案 1 :(得分:4)

在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

答案 2 :(得分:2)

  

打印(STR(列表).replace(' ['' {'。)代替(']''} '))

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

答案 3 :(得分:1)

如果你想得到hacky:

/api/v1/users/:id

答案 4 :(得分:1)

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

一个。通过将{]替换为{}来修改str(alist)。 @Garret修改了两次调用str.replace的str结果。另一种方法是使用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的相对结果大致相同。

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

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

答案 5 :(得分:0)

('{}'.format(the_list)).replace('[','{').replace(']','}')

结果

{1, 2, 3}

答案 6 :(得分:0)

使用Python 3.6 f-strings:

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

format用于Python< 3.6:

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

或旧的,但未弃用的%

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