【问题标题】:Printing a 2D list in python without the commas在没有逗号的python中打印二维列表
【发布时间】:2012-07-29 14:14:27
【问题描述】:

我想在 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] ... ]

对我应该如何做同样的事情有任何见解吗?

谢谢!

【问题讨论】:

    标签: python list


    【解决方案1】:

    简单:用repr转换成字符串后用空格替换逗号。

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

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

    【讨论】:

    • 编辑:“简单:只需用空格替换逗号转换为字符串后
    • mutzmatron:即使它不是字符串列表也可以使用
    • @user1249518 如果您的数据包含逗号,这也会中断。
    【解决方案2】:

    有几种方法:

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

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        【解决方案4】:

        一个通用的、安全的和递归的解决方案,如果数据包含逗号就可以工作:

        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)。

        【讨论】:

        • 此解决方案不会处理不继承自 list 的元组、迭代器或类似列表的对象。我猜这个问题只是关于list,但在 Python 中很容易解决一般问题;看我的回答。
        【解决方案5】:

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

        【讨论】:

          【解决方案6】:

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

          你想要什么?

          【讨论】:

            【解决方案7】:

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

            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) 检查?原因如下:

            How to check if an object is a list or tuple (but not string)?

            【讨论】:

            • 我可能会使用 isinstance(seq, collections.abc.Iterable) 而不是 try/except。
            • 我没有看到collections.abc.Iterable,但我看到collections.Iterable...当我检查时,isinstance(x, collections.Iterable) 成功,而x 是一个列表、一个迭代器或一个生成器.只要您不需要使用无需费心从合适的 Python 基类型继承的定制类,isinstance() 检查就可以工作,并且应该会明显更快。
            • collections.abc 是 Python 3。
            • @steveha: isinstance(x, Iterable) 在任何具有__iter__ 方法的对象上成功。 collections ABC 使用子类挂钩来自定义 isinstance
            • 哇,这就是我喜欢 StackOverflow 的地方。像这样学习很酷的东西。所以基本上如果for x in foo 会成功,那么isinstance(foo, Iterable) 会返回True?你们把这个想法卖给了我。我会编辑答案。
            猜你喜欢
            • 2014-03-06
            • 2017-09-11
            • 1970-01-01
            • 2017-11-22
            • 2020-07-29
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多