0

巣のどこかに絡まってしまいます。

次のような python オブジェクトのリストがあります。

notes = [
     {'id':1,
      'title':'title1',
      'text':'bla1 bla1 bla1',
      'tags':['tag1a', ' tag1b', ' tag1c']},
     {'id':2,
      'title':'title2',
      'text':'bla2 bla2 bla2',
      'tags':[' tag2a', ' tag2b', ' tag2c']},
     {'id':3,
      'title':'title3',
      'text':'bla3 bla3 bla3',
      'tags':[' tag3a', ' tag3b', ' tag3c']}] 

等々。

リスト内の各辞書にアクセスして、左側の空白を取り除き、辞書のリストを返そうとしています。唯一の違いは、タグの不要な空白が削除されていることです。

次のコードは私が取り組んでいるものですが、正しくなく、必要な結果を得るために何をしているのかわかりません。

notes_cleaned = []
for objs in notes:
    for items in objs:
        notes_cleaned.append({'text':n['text'], 'id':n['id'], 'tags':[z.lstrip(' ') for z in n['tags']], 'title':n['title']})

これにより、文字列インデックスを使用できないというエラーが表示されますが、これは理解できますが、正しく行う方法がわかりません。次のように、各辞書を反復処理する必要があることがわかっているためです。

for objs in notes:
    for items in objs:
        print items, objs[items]

しかし、具体的にタグリストを掘り下げながら、辞書を再構築する最後の部分に到達する方法について混乱しています。

ここで何が欠けていますか(間違いなく何かが欠けていることを知っています)。

4

3 に答える 3

2

これで十分だと思います。

for note in notes:
    note['tags']= [t.strip() for t in note['tags']]

(メモの)コピーを実際に操作する必要がある場合は、簡単に入手できます。copy= map(dict, notes)

于 2012-12-22T02:13:37.947 に答える
2
    python 3.2

     # if you want the dict which value is list and string within the list stripped 

     [{i:[j.strip() for j in v] for i,v in k.items()if isinstance(v,list)} for k in notes]



     # if you want the dict which value is list and those string within the list 
    stripped which has whitespace

     [{i:[j.strip() for j in v if " " in j] for i,v in k.items()if isinstance(v,list)}
                   for k in n]
于 2012-12-22T14:48:14.877 に答える
1

「タグ」のみを削除する必要があると仮定すると、次のコードが機能するはずです。

def clean(items):
    clean = []
    for objs in items:
        nObj = {}
        for item, obj in objs.iteritems():
            if item != "tags":
                nObj[item] = obj
            else:
                nObj["tags"] = [n.lstrip() for n in obj]
        clean.append(nObj)
    return clean
于 2012-12-22T02:14:01.500 に答える