English 中文(简体)
打印 Python 输出输出的最佳方式
原标题:Best way to print list output in python
  • 时间:2012-05-25 19:02:12
  •  标签:
  • python
  • list

我有这样的列表 < code> list 和 < code> list 列表 < /code> 的 < code> 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])
...

它产生了这个输出,这就是我所希望的 输出

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

现在,我的问题是有更多的 cleaner和更好的 方式来实现我所期望的输出,或者这是 best(短、易读) 的可能方式。

最佳回答

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

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

但我认为你不会得到任何 根本上"更好"的东西

问题回答

以下 环的 < code> 将同时将打印和合并操作合并成一行。

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

它可能不象一个全环解决方案那样完全可读,但以下内容仍然可读而且较短:

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

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

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

您可能认为是干净的, 但我不认为, 您的程序的其余部分 需要现在您的数据结构和如何打印 。 IMHO 应该包含在数据类中, 这样您就可以做 < code> 打印我的列表 < / code > 并获得想要的结果 。

如果你把这一点与mgilson建议使用字典结合起来(我甚至建议使用一个有秩序的字典),

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

不需要程序的其他部分 需要知道打印此数据的细节 。





相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签