在Python中打印一个二维列表,不带逗号

3

我想在Python中打印一个二维列表,但不带逗号。

不要打印下面这样带逗号的格式:

[[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] ... ]

任何关于我应该如何做相同事情的见解?
谢谢!
7个回答

5

简单易懂:只需使用repr将逗号转换为空格并转换为字符串即可。

def repr_with_spaces(lst):
    return repr(lst).replace(",", " ")

(这适用于整数列表,但不一定适用于其他任何东西。)

简单:将逗号替换为空格 在转换为字符串之后 - jmetz
mutzmatron:尽管它不是字符串列表,但这仍然有效。 - Aniruddh Chaturvedi
2
@user1249518 如果你的数据包含逗号,这也会出现错误。 - millimoose

3

这里有一个通用的解决方案。使用指定的分隔符,以及指定的左右括号字符,将一个序列转换为一个字符串。

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) 检查?这就是原因:

如何检查一个对象是否为列表或元组(但不是字符串)?


2
我可能会使用 isinstance(seq, collections.abc.Iterable) 而不是 try/except。 - ecatmur
我没有看到collections.abc.Iterable,但我看到了collections.Iterable...当我检查时,isinstance(x, collections.Iterable)成功了,其中x是一个列表、迭代器或生成器。只要你不需要使用那些不从适当的Python基本类型继承的自定义类,isinstance()检查就可以工作,并且应该会更快。 - steveha
@larsmans -- 我的理解是 collections.abc.Iterable 比 Python 2.x 中的 collections.Iterable 更智能?在 Python 2.x 中,是否有可能通过自定义类来欺骗上述代码,该类仅继承自 object 并定义其自己的方法以使其可迭代? - steveha
@larsmans -- 好的,我再仔细研究了一下,现在我明白了。Python 2.6引入了collections.Iterable和其他抽象基类在collections中。我最初编写的代码适用于Python 2.5及更早版本,但对于Python 2.6及更高版本,我更喜欢这种方式。任何对抽象基类感兴趣的人都应该阅读PEP:http://www.python.org/dev/peps/pep-3119/ - steveha
有一种情况下这个解决方案不适用,而 try/except 会起作用。在 Python 中,如果你在类中实现了 .__getitem__(),即使你没有实现 .__iter__(),它也是可迭代的。我认为我更喜欢 Iterable 测试;如果你想让你的类可迭代,你应该实现 .__iter__()。这里有一个很棒的讨论:https://dev59.com/dXNA5IYBdhLWcg3whuV_ - steveha
显示剩余4条评论

2
一个通用、安全和递归的解决方案,如果数据包含逗号,则可以使用该解决方案:
def my_repr(o):
    if isinstance(o, list):
        return '[' + ' '.join(my_repr(x) for x in o) + ']'
    else:
        return repr(o)

CPython实现的list_repr使用基本上是这个算法(使用_PyString_Join函数)。

这个解决方案无法处理元组、迭代器或不继承自list的类列表对象。我猜问题只是关于list的,但在Python中解决这个通用问题很容易;请看我的回答。 - steveha

0
有几种方法:
your_string.replace(',',' ') 

' '.join(your_string.split(','))

0

好的,作为一个应用于变量“a”中数组的一行代码:

print "[" + ' '.join(map(lambda row: "[" + ' '.join(map(str, row)) + "] ", a)) + "]"

0
你可以使用 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)

ideone 示例:http://ideone.com/g1VdE


0

str([1,2],[3,4]).replace(","," ")

你想要什么?


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接