【问题标题】:Best way to print list output in python在python中打印列表输出的最佳方法
【发布时间】:2012-05-29 07:11:35
【问题描述】:

我有一个像这样的list 和一个list of list

>>> list2 = [["1","2","3","4"],["5","6","7","8"],["9","10","11","12"]]
>>> list1 = ["a","b","c"]

我压缩了以上两个列表,以便我可以按索引匹配它们的值索引。

>>> mylist = zip(list1,list2)
>>> mylist
[('a', ['1', '2', '3', '4']), ('b', ['5', '6', '7', '8']), ('c', ['9', '10', '11', '12'])]

现在我尝试使用上面的mylist 打印输出

>>> for item in mylist:
...     print item[0]
...     print "---".join(item[1])
...

结果是我的desired output

a
1---2---3---4
b
5---6---7---8
c
9---10---11---12

现在,我的问题是有更多的cleaner and better 方式来实现我想要的输出,或者这是best(short and more readable) 可能的方式。

【问题讨论】:

  • 不是真的,你可以写 for name,lst in mylist: print name 而不是索引,但我认为仅此而已
  • 另一条评论——如果这两个列表真的要并排维护,您可能需要考虑将它们存储为字典...
  • @mgilson:谢谢。我一定会探索这个选项。

标签: python list


【解决方案1】:

好吧,你可以避免一些临时变量并使用更好的循环:

for label, vals in zip(list1, list2):
    print label
    print '---'.join(vals)

不过,我不认为你会从根本上得到任何“更好”的东西。

【讨论】:

  • 感谢您的回答。还有一个问题是有任何网站,如 python doc 或我可以寻找 best python practice 的网站。
  • @Noob 这是 PEP 8 Python 风格指南,以防您以前没有看过:python.org/dev/peps/pep-0008
【解决方案2】:

下面的for 循环会将打印和连接操作合并到一行中。

 for item in zip(list1,list2):
     print '{0}\n{1}'.format(item[0],'---'.join(item[1]))

【讨论】:

    【解决方案3】:

    它的可读性可能不如完整的循环解决方案,但以下内容仍然可读且更短:

    >>> zipped = zip(list1, list2) 
    >>> print '\n'.join(label + '\n' + '---'.join(vals) for label, vals in zipped)
    a
    1---2---3---4
    b
    5---6---7---8
    c
    9---10---11---12
    

    【讨论】:

      【解决方案4】:

      这是实现结果的另一种方法。它更短,但我不确定它是否更具可读性:

      print '\n'.join([x1 + '\n' + '---'.join(x2) for x1,x2 in zip(list1,list2)])
      

      【讨论】:

        【解决方案5】:

        您可能认为干净但我不认为是您程序的其余部分现在需要数据的结构以及如何打印它。恕我直言,应该包含在数据类中,因此您只需执行print mylist 即可获得所需的结果。

        如果您将其与 mgilson 的建议结合使用字典(我什至建议使用 OrderedDict),我会这样做:

        from collections import OrderedDict
        
        class MyList(list):
            def __init__(self, *args):
                list.__init__(self, list(args))
        
            def __str__(self):
                return '---'.join(self)
        
        class MyDict(OrderedDict):
            def __str__(self):
                ret_val = []
                for k, v in self.iteritems():
                    ret_val.extend((k, str(v)))
                return '\n'.join(ret_val)
        
        mydata = MyDict([
            ('a', MyList("1","2","3","4")),
            ('b', MyList("5","6","7","8")),
            ('c', MyList("9","10","11","12")),
        ])
        
        print mydata
        

        不需要程序的其余部分知道打印此数据的详细信息。

        【讨论】:

          猜你喜欢
          • 2011-12-07
          • 2014-08-03
          • 1970-01-01
          • 2019-09-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2010-09-26
          • 2019-10-05
          相关资源
          最近更新 更多