简体   繁体   English

打印/输出时如何从列表中删除方括号

[英]How to remove the square brackets from a list when it is printed/output

I have a piece of code that does everything I need it to do and now I am making it look better and refining it. 我有一段代码可以完成我需要做的所有事情,现在我使它看起来更好并得到了完善。 When I print the outcome, I find that the list in the statement is in square brackets and I cannot seem to remove them. 打印结果时,我发现语句中的列表在方括号中,并且似乎无法删除它们。

You can use map() to convert the numbers to strings, and use " ".join() or ", ".join() to place them in the same string: 您可以使用map()将数字转换为字符串,并使用" ".join()", ".join()将它们放在同一字符串中:

mylist = [4, 5]
print(" ".join(map(str, mylist)))
#4 5
print(", ".join(map(str, mylist)))
#4, 5

You could also just take advantage of the print() function: 您还可以利用print()函数:

mylist = [4, 5]
print(*mylist)
#4 5
print(*mylist, sep=", ")
#4, 5

Note: In Python2, that won't work because print is a statement, not a function. 注意:在Python2中,这是行不通的,因为print是一个语句,而不是一个函数。 You could put from __future__ import print_function at the beginning of the file, or you could use import __builtin__; getattr(__builtin__, 'print')(*mylist) 您可以将from __future__ import print_function放在文件的开头,也可以使用import __builtin__; getattr(__builtin__, 'print')(*mylist) from __future__ import print_function import __builtin__; getattr(__builtin__, 'print')(*mylist)

If print is a function (which it is by default in Python 3), you could unpack the list with * : 如果print是一个函数(在Python 3中是默认值),则可以使用* 解压缩列表:

>>> L = [3, 5]
>>> from __future__ import print_function
>>> print(*L)
3 5

You could convert it to a string instead of printing the list directly: 您可以将其转换为字符串,而不是直接打印列表:

print(", ".join(LIST))

If the elements in the list are not strings, you can convert them to string using either repr() or str() : 如果列表中的元素不是字符串,则可以使用repr()或str()将它们转换为字符串:

LIST = [1, "printing", 3.5, { "without": "brackets" }]
print( ", ".join( repr(e) for e in LIST ) )

Which gives the output: 给出输出:

1, 'printing', 3.5, {'without': 'brackets'}

You could do smth like this: 您可以这样做:

separator = ','
print separator.join(str(element) for element in myList) 

Why don't you display the elements in the list one by one using the for loop instead of displaying an entire list at once like so: 为什么不使用for循环一个接一个地显示列表中的元素,而不是像这样一次显示整个列表:

# l - list
for i in range(0, len(l)):
    print l[i],

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM