簡體   English   中英

在python中打印列表輸出的最佳方法

[英]Best way to print list output in python

我有一個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 label, vals in zip(list1, list2):
    print label
    print '---'.join(vals)

不過,我認為你不會從根本上獲得任何“更好”的東西。

以下for循環將打印和連接操作合並為一行。

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

它可能不像完整循環解決方案那樣可讀,但以下內容仍然可讀且更短:

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

這是實現結果的另一種方式。 它更短,但我不確定它更具可讀性:

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

您可能認為干凈,但我不認為,您的其余程序現在需要您的數據結構以及如何打印它。 恕我直言,應該包含在數據類中,這樣你就可以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

不需要程序的其余部分需要知道打印此數據的細節。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM