第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機(jī)立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

python append 和 列表解析

python append 和 列表解析

開滿天機(jī) 2019-02-21 04:11:33
問題:將數(shù)據(jù)庫中查出的數(shù)據(jù)(列表中包含元組)轉(zhuǎn)換為列表中字典。 原數(shù)據(jù)結(jié)構(gòu),從數(shù)據(jù)庫查出: cur = [("t1", "d1"), ("t2", "d2")] 轉(zhuǎn)換后數(shù)據(jù)結(jié)構(gòu): [{'description': 'd1', 'title': 't1'}, {'description': 'd2', 'title': 't2'}] 方法一,使用append, 出現(xiàn)錯誤結(jié)果 pythoncur = [("t1", "d1"), ("t2", "d2")] post_dict = {} posts = [] for row in cur: post_dict['title'] = row[0] post_dict['description'] = row[1] print "post_dict:",post_dict posts.append(post_dict) print "posts:",posts 方法一運(yùn)行結(jié)果: pythonpost_dict: {'description': 'd1', 'title': 't1'} posts: [{'description': 'd1', 'title': 't1'}] post_dict: {'description': 'd2', 'title': 't2'} posts: [{'description': 'd2', 'title': 't2'}, {'description': 'd2', 'title': 't2'}] 方法二,使用列表解析,結(jié)果正常 pythoncur = [("a", "a1"), ("b", "b1")] posts = [] posts = [dict(title=row[0], description=row[1]) for row in cur] print "posts:",posts 方法二運(yùn)行結(jié)果,正常 pythonposts: [{'description': 'd1', 'title': 't1'}, {'description': 'd2', 'title': 't2'}]
查看完整描述

2 回答

?
蕭十郎

TA貢獻(xiàn)1815條經(jīng)驗(yàn) 獲得超13個贊

方法一中,你的post_dict是一個字典對象,for循環(huán)的操作都是在更新這個對象的keyvalue,自始至終就這一個對象,append多少次都一樣。

把字典對象放在循環(huán)內(nèi)創(chuàng)建即可:

pythoncur = [("t1", "d1"), ("t2", "d2")] 
posts = []
for row in cur:
    post_dict = {}
    post_dict['title'] = row[0]
    post_dict['description'] = row[1]
    print "post_dict:",post_dict
    posts.append(post_dict)
    print "posts:",posts

優(yōu)先考慮列表解析,另,本例的tupel列表可以用循環(huán)解包,大致如下:

pythonIn [1]: cur = [("t1", "d1"), ("t2", "d2")]

In [2]: r = [{'description': description, 'title': title} for description, title in cur]

In [3]: r
Out[3]: [{'description': 't1', 'title': 'd1'}, {'description': 't2', 'title': 'd2'}]
查看完整回答
反對 回復(fù) 2019-03-01
?
猛跑小豬

TA貢獻(xiàn)1858條經(jīng)驗(yàn) 獲得超8個贊

方法一的循環(huán)中,post_dict始終指向的是同一個對象。
在for循環(huán)中,使用匿名對象就可以了:

for row in cur:
    posts.append({'title':row[0],'description':row[1]})
查看完整回答
反對 回復(fù) 2019-03-01
  • 2 回答
  • 0 關(guān)注
  • 544 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號