将嵌套列表打印为字符串以供显示

Printing nested list as string for display

我有这个代码:

data = [["apple", 2], ["cake", 7], ["chocolate", 7], ["grapes", 6]]

我想在 运行 我的代码时很好地显示它,这样您就不会看到语音标记或方括号,像这样显示它:

apple, 2
cake, 7
chocolate, 7
grapes, 6

我查看了这个网站以帮助我:

http://www.decalage.info/en/python/print_list

但是他们说要使用 print("\n".join),只有当列表中的值都是字符串时才有效。

我该如何解决这个问题?

一般来说,像pprint这样的东西会给你输出来帮助你理解对象的结构。

但对于您的特定格式,您可以通过以下方式获取该列表:

data=[["apple",2],["cake",7],["chocolate",7],["grapes",6]]

for (s,n) in data: print("%s, %d" % (s,n))
# or, an alternative syntax that might help if you have many arguments
for e in data: print("%s, %d" % tuple(e))

两者输出:

apple, 2
cake, 7
chocolate, 7
grapes, 6

或者你可以用非常复杂的方式来做,所以每个嵌套列表都会打印在它自己的行中,而每个嵌套元素也不是。类似于 "ducktyping":

def printRecursively(toPrint):
    try:
        #if toPrint and nested elements are iterables
        if toPrint.__iter__() and toPrint[0].__iter__():
            for el in toPrint:
                printRecursively(el)
    except AttributeError:
        #toPrint or nested element is not iterable
        try:
            if toPrint.__iter__():
                print ", ".join([str(listEl) for listEl in toPrint])
        #toPrint is not iterable
        except AttributeError:
            print toPrint
data = [["apple", 2], ["cake", 7], [["chocolate", 5],['peanuts', 7]], ["grapes", 6], 5, 6, 'xx']
printRecursively(data)

希望你喜欢:)