簡體   English   中英

嵌套字典理解

[英]Nested dict comprehension

在以下代碼中,

[{word: score_tweet(tweet) for word in tweet} for tweet in tweets]

我得到的字典列表:

[{u'soad': 0.0, u'<3': 0.0}, {u'outros': 0.0, u'acredita': 0.0}]

我只想獲得一個簡單的字典,例如:

{u'soad': 0.0, u'<3': 0.0, u'outros': 0.0, u'acredita': 0.0}

我應該如何更改我的代碼? 注意:我正在使用Python 2.7。

{word: score_tweet(tweet) for tweet in tweets for word in tweet}

for循環移至dict理解中:

{word: score_tweet(tweet) for tweet in tweets for word in tweet}

請記住,一行中的兩個for循環很難閱讀。 我會做這樣的事情:

scores = {}

for tweet in tweets:
    tweet_score = score_tweet(tweet)

    for word in tweet:
        scores[word] = tweet_score

您需要一個中間步驟。

words = []
tweets = ["one two", "three four"]
for tweet in tweets:
    words.extend(tweet.split())
scores = {word: score_tweet(word) for word in words}
"""
[{u'soad': 0.0, u'<3': 0.0}, {u'outros': 0.0, u'acredita': 0.0}] 
->
{u'soad': 0.0, u'<3': 0.0, u'outros': 0.0, u'acredita': 0.0}
"""
tweets_merged = {}
tweets = [{u'soad': 0.0, u'<3': 0.0}, {u'outros': 0.0, u'acredita': 0.0}]
for tweet in tweets:    
    tweets_merged = dict(tweets_merged.items() + tweet.items())
print tweets_merged

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM