[英]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
或者,您也可以采用非常复杂的方式进行操作,因此每个嵌套列表都将在其自己的行中打印,而每个嵌套元素都不会。 像“鸭嘴兽”这样的东西:
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)
希望你喜欢 :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.