还是有更好的方法来快速输出数组的内容(多维或非多维)。谢谢。
还是有更好的方法来快速输出数组的内容(多维或非多维)。谢谢。
Answers:
您正在寻找repr临时加入功能。
http://docs.python.org/2/library/functions.html#func-repr
print repr(variable)
在Python 3中,print不再是一个语句,因此将是:
print( repr(variable) )
from pprint import pprint
student = {'Student1': { 'Age':10, 'Roll':1 },
'Student2': { 'Age':12, 'Roll':2 },
'Student3': { 'Age':11, 'Roll':3 },
'Student4': { 'Age':13, 'Roll':4 },
'Student5': { 'Age':10, 'Roll':5 }
}
pprint(student)
您可以尝试以下一种方法:
https://github.com/sha256/python-var-dump
您可以简单地使用安装 pip
pip install var_dump
免责声明:我写的:)
print并且pprint对于定义理智的对象表示形式的内置数据类型或类非常有用。如果要完全转储任意对象,则必须自己滚动。这并不难:只需创建一个递归函数即可,基本情况是任何非容器内置数据类型,然后递归情况将函数应用于容器的每个项目或对象的每个属性,就可以得到该递归函数。使用dir()或inspect模块。
有适用于python的print_r https://github.com/marcbelmont/python-print_r/wiki, 但最好使用标准模块
my_list = list(enumerate([1,2,3,4,5,6,7,8,9],0))
print(my_list)
将打印[[0,1),(1,2),(2,3),(3,4),(4,5),(5,6),(6,7),(7,8) ,((8,9)]
如果要格式化variable为字符串,可以执行以下操作:
s = repr(variable)
无论类型如何,它都可以工作,并且不需要任何导入。
如果要将对象的内容及其类型包括在单个字符串中:
if hasattr(variable, "__dict__"):
s = "{}: {}".format(variable, vars(variable))
else:
s = repr(variable)
对于简单的测试视图,我使用HttpResponse。测试来自表单,变量,字符串,ID,而非对象的请求
from django.http.response import HttpResponse
HttpResponse(variable)
def add_comment(request, id):
return HttpResponse(id)