一、列表前戏:
#例1 v1 = [1,2,3,4] v1.append(123) print(v1)#[1, 2, 3, 4, 123] #例2 v1 = {'k1':'v1'} v1['k2'] = 'v2' print(v1)#{'k1': 'v1', 'k2': 'v2'} #例3 data = [ [11,22,33], [44,55,66] ] data1=data[0] data2 = data1.append(data[1]) print(data1)#[11, 22, 33, [44, 55, 66]] # # data=data[0].append(data[1]) print(data)#[[11, 22, 33, [44, 55, 66]], [44, 55, 66]] print(data[1])#[44, 55, 66] data[1].append(77) print(data)#[[11, 22, 33, [44, 55, 66, 77]], [44, 55, 66, 77]] print(data[0][3])#[44, 55, 66, 77] ##例4 data = [ {'k1':'v1'}, {'k2':'v2'} ] for item in data: item['kk'] = 'vv' print(data)#[{'k1': 'v1', 'kk': 'vv'}, {'k2': 'v2', 'kk': 'vv'}] #引用类型
二、原理
msg_list = [ {'id':1,'content':'xxx','parent_id':None}, {'id':2,'content':'xxx','parent_id':None}, {'id':3,'content':'xxx','parent_id':None}, {'id':4,'content':'xxx','parent_id':1}, {'id':5,'content':'xxx','parent_id':4}, {'id':6,'content':'xxx','parent_id':2}, {'id':7,'content':'xxx','parent_id':5}, {'id':8,'content':'xxx','parent_id':3}, ] #python里面的apend之类的东西都是引用的原来数据的内存地址,对原数据进行操作的话 #我们引用的数据也会发生一样的变化(字典列表之类的) #浙江片子的方法 # for i in msg_list: # i['child']=[] # for i in range(len(msg_list)-1,-1,-1): # if msg_list[i]['parent_id']: # msg_list[msg_list[i]['parent_id'] - 1]['child'].append(msg_list[i]) # new_msg_list = [i for i in msg_list if i['parent_id'] is None] # print(new_msg_list)
冒泡排序的效率比较低,因为要多加几层循环
#老师讲的方法 # v=[row.setdefault('child',[]) for row in msg_list] #这是一个列表生成式,其中列表生成式前缀不能是表达式(不能带等于号),这和底下的第一个for循环的作用是一样的,给每一个元素加一个'child':[] # print(msg_list) #如果我们想加快索引(快点找到数据的话)就建一个字典的数据结构 msg_list_dict={} #加快索引,节省时间 for item in msg_list: item['child']=[] #相当于加一个键值对,{'id':1,'content':'xxx','parent_id':None,'child':[]} msg_list_dict[item['id']]=item #字典中key为item['id'],value为item
#
msg_list_dict[item['id']]=item 相当于如下字典
msg_list_dict = {
1:{'id':1,'content':'xxx','parent_id':None,'child':}
2:{'id':2,'content':'xxx','parent_id':None,'child':}
''''''
}
#把字典数据结构填上数据,能够加快索引,而且我们数据还是占得原来的内存空间 #我们只是引用了数据的内容空间,所以不存在新的数据结构浪费空间一说 result=[] for item in msg_list: pid=item['parent_id'] if pid: #如果parent_id不为空,说明它是子级,要把自己加入对应的父级 msg_list_dict[pid]['child'].append(item) else: #如果为空,说明他是父级,要把它单独领出来用 result.append(item) #result就是我们最终要的结果,因为这里面全是引用,所有数据的内存地址都没有变 #只不过被多个数据结构引用了而已 print(result)
多级评论(评论楼)具体实现
def article(request,site,nid):#文章 """ 评论 :param request: :param site: :param nid: :return: """ blog = models.Blog.objects.filter(site=site).first() if not blog: return redirect('/') #按照:分类,标签,时间 #分类 category_list = models.Article.objects.filter(blog=blog).values('category_id','category__title').annotate(ct=Count('nid')) print(category_list) #标签 tag_list = models.Article2Tag.objects.filter(article__blog=blog).values('tag_id','tag__title').annotate(ct=Count('id')) print(tag_list) #时间 date_list = models.Article.objects.filter(blog=blog).extra(select={'ctime':"date_format('%%Y-%%m',create_time)"}).values('ctime').annotate(ct=Count('nid')) print(date_list) obj = models.Article.objects.filter(blog=blog,nid=nid).first() #############################评论############################## msg_list = [ {'id': 1, 'content': '写的太好了', 'parent_id': None}, {'id': 2, 'content': '你说得对', 'parent_id': None}, {'id': 3, 'content': '顶楼上', 'parent_id': None}, {'id': 4, 'content': '你眼瞎吗', 'parent_id': 1}, {'id': 5, 'content': '我看是', 'parent_id': 4}, {'id': 6, 'content': '鸡毛', 'parent_id': 2}, {'id': 7, 'content': '你是没呀', 'parent_id': 5}, {'id': 8, 'content': '惺惺惜惺惺想寻', 'parent_id': 3}, ] msg_list_dict = {} for item in msg_list: item['child'] = [] msg_list_dict[item['id']] = item # msg_list_dict用于查找,msg_list result = [] for item in msg_list: pid = item['parent_id'] if pid: msg_list_dict[pid]['child'].append(item) else: result.append(item) ################打印################## from utils.comment import comment_tree comment_str = comment_tree(result) return render( request, 'article_detail.html', { 'blog':blog, 'category_list':category_list, 'tag_list':tag_list, 'date_list':date_list, 'obj':obj, 'comment_str':comment_str } )
def comments(request,nid): response = {'status':True,'data':None,'msg':None} try: msg_list = [ {'id': 1, 'content': '写的太好了', 'parent_id': None}, {'id': 2, 'content': '你说得对', 'parent_id': None}, {'id': 3, 'content': '顶楼上', 'parent_id': None}, {'id': 4, 'content': '你眼瞎吗', 'parent_id': 1}, {'id': 5, 'content': '我看是', 'parent_id': 4}, {'id': 6, 'content': '鸡毛', 'parent_id': 2}, {'id': 7, 'content': '你是没呀', 'parent_id': 5}, {'id': 8, 'content': '惺惺惜惺惺想寻', 'parent_id': 3}, ] msg_list_dict = {} for item in msg_list: item['child'] = [] msg_list_dict[item['id']] = item ########################msg_list_dict用于查找msg_list################################# result = [] for item in msg_list: pid = item['parent_id'] if pid: msg_list_dict[pid]['child'].append(item) else: result.append(item) response['data'] = result except Exception as e: response['status'] = False response['msg'] = str(e) return HttpResponse(json.dumps(response))
{% extends 'layout.html' %} {% block xx %} <link rel="stylesheet" href="/static/plugins/bootstrap-3.3.7-dist/css/bootstrap.css"> <link rel="stylesheet" href="/static/plugins/font-awesome-4.7.0/css/font-awesome.css"> <style> .pg-body{ 1600px; float: right; margin-left: 300px; border: 1px solid #ced7ce; border-right: 3px solid #ced7ce; border-bottom: 3px solid #ced7ce; background: #fff; left: 0; } .pg-body .up_down{ margin-top: 100px; } .pg-body .up_down .add-up{ float: right; margin-right: 30px; } .pg-body .up_down .add-down{ float: right; margin-right: 30px; } .comment{ margin-left: 30px;/*margin-left 属性设置元素的左外边距30px*/ } </style> <div class="pg-body"> <h3><a class="body-right1" href="{{ blog.site }}/p/{{ row.nid }}.html">{{ obj.title }}</a></h3> <div class="body-right2">{{ obj.articledetail.content|safe }}</div> <div class="up_down"> <a class="add-up" onclick="up(this,{{ obj.nid }},1);"> <span>赞</span> <i>{{ obj.up_count }}</i> </a> <a class="add-down" onclick="down(this,{{ obj.nid }},0);"> <span>踩</span> <i>{{ obj.down_count }}</i> </a> <h3>评论</h3> <div id="commentArea"></div> {# {{ comment_str|safe }}#} </div> </div>
<script src="/static/jquery-3.2.1.js"></script> <script> /* 1.调用对象的方法时,通过调用类的prototype中的方法,可以扩展 2.正则表达式 /w+/g 3.字符串replace ''.replace('alex','sb') ''.replace(/w+/,'sb') ''.replace(/w+/g,'sb') ''.replace(/(w+)/g,function(k,kk){return 11;}); dt = new Date(); dt.getDate(); */ {# String.prototype.Format = function(arg){#} {# console.log(this,arg);#} {# return '666';#} {# };#} String.prototype.Format = function(arg){ /* this,当前字符串 "i am {name1},age is {age9}" arg,Format方法传入的参数{name:'alex',age:18} return,格式化之后获取的新内容 i am alex,age is 18 */ var temp = this.replace(/{(w+)}/g,function (k,kk) { return arg[kk]; }); return temp; }; $(function () { //发送Ajax请求,获取所有评论信息 //列表 //js生成结构 $.ajax({ url:'/comments-{{ obj.nid }}.html', type:'GET', dataType:"JSON", success:function(arg){ if(arg.status){ var comment = commentTree(arg.data); $('#commentArea').append(comment); }else{ alert(arg.msg); } } }) }); function commentTree(commentList){ var comment_str = "<div class='comment'>"; $.each(commentList,function (k,row) { /* k代表索引,row代表评论 */ //var temp = "<div class='content'>" + row.content+"</div>"; 字符串拼接 var temp = "<div class='content'>{content}</div>".Format({content:row.content}); /*自定义Format格式化方法*/ comment_str += temp; if (row.child.length > 0){ comment_str += commentTree(row.child); /*如果孩子child的长度大于0时,递归*/ } }); comment_str += '</div>'; return comment_str; } </script>
三、Python 字典(Dictionary) setdefault()方法
描述
Python 字典 setdefault() 函数和get() 方法类似, 如果键不存在于字典中,将会添加键并将值设为默认值。
语法
setdefault()方法语法:
dict.setdefault(key, default=None)
参数
- key -- 查找的键值。
- default -- 键不存在时,设置的默认键值。
返回值
如果字典中包含有给定键,则返回该键对应的值,否则返回为该键设置的值。