[英]Printing a 2D list in python without the commas
我想在沒有逗號的情況下在python中打印2D列表。
而不是打印
[[0,0,0,0,0,1,1,1,1,1,1],[0,0,0,0,0,0,1,1,1,1,0,0,0,1,1,0,0,1,1,0,1],[1,1,1] ... ]
我想要打印
[[0 0 0 0 0 1 1 1 1 1 1 1] [0 0 0 0 0 0 1 1 1 1 0 0 0 1 1 0 0 1 1 0 1] [1 1 1] ... ]
有關我應該如何做的任何見解?
謝謝!
簡單:在轉換為帶有repr
的字符串后,只需用空格替換逗號。
def repr_with_spaces(lst):
return repr(lst).replace(",", " ")
(這適用於整數列表,但不一定適用於其他任何內容。)
這是一個通用的解決方案。 使用指定的分隔符將序列轉換為字符串,並指定左右包圍字符。
lst = [[0,0,0,0,0,1,1,1,1,1,1],[0,0,0,0,0,0,1,1,1,1,0,0,0,1,1,0,0,1,1,0,1],[1,1,1]]
import sys
if sys.version_info[0] >= 3:
basestring = str
try:
from collections.abc import Iterable
except ImportError:
from collections import Iterable
def str_seq(seq, sep=' ', s_left='[', s_right=']'):
if isinstance(seq, basestring):
return seq
if isinstance(seq, Iterable):
s = sep.join(str_seq(x, sep, s_left, s_right) for x in seq)
return s_left + s + s_right
else:
return str(seq)
print(str_seq(lst))
為什么代碼有isinstance(seq, basestr)
檢查? 原因如下:
一種通用,安全和遞歸的解決方案,如果數據包含逗號,則可以使用:
def my_repr(o):
if isinstance(o, list):
return '[' + ' '.join(my_repr(x) for x in o) + ']'
else:
return repr(o)
list_repr
的CPython實現使用必不可少的算法(使用_PyString_Join
)。
有幾種方法:
your_string.replace(',',' ')
' '.join(your_string.split(','))
好吧,作為一個單行應用於變量“a”中的數組:
print "[" + ' '.join(map(lambda row: "[" + ' '.join(map(str, row)) + "] ", a)) + "]"
你可以使用str.join()
:
lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
def format_list(items):
list_contents = ' '.join(str(it) for it in items) # convert contents to string too
return '[{}]'.format(list_contents) # wrap in brackets
formatted = format_list(format_list(l) for l in lists)
例如: http ://ideone.com/g1VdE
是
str([1,2],[3,4]).replace(","," ")
你想要什么?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.